ydb.c 83.5 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."
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul 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

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

25 26
#include "ydb-internal.h"

27
#include "brt-internal.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
28
#include "cachetable.h"
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
29 30
#include "log.h"
#include "memory.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
31

Rich Prohaska's avatar
Rich Prohaska committed
32

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
33 34
/** The default maximum number of persistent locks in a lock tree  */
const u_int32_t __toku_env_default_max_locks = 1000;
Rich Prohaska's avatar
Rich Prohaska committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

/* 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);
53 54 55
static int toku_env_set_data_dir(DB_ENV * env, const char *dir);
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir);
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir);
Rich Prohaska's avatar
Rich Prohaska committed
56 57

static inline void env_add_ref(DB_ENV *env) {
58
    ++env->i->ref_count;
Rich Prohaska's avatar
Rich Prohaska committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
}

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);
80
static int toku_db_cursor(DB *db, DB_TXN * txn, DBC **c, u_int32_t flags, int is_temporary_cursor);
Rich Prohaska's avatar
Rich Prohaska committed
81 82 83 84 85 86 87 88 89 90

/* 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);
Yoni Fogel's avatar
Yoni Fogel committed
91
static int toku_save_original_data(DBT* dst, DBT* src);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
92

Rich Prohaska's avatar
Rich Prohaska committed
93
/* misc */
Yoni Fogel's avatar
Yoni Fogel committed
94
static char *construct_full_name(const char *dir, const char *fname);
95
static int do_associated_inserts (DB_TXN *txn, DBT *key, DBT *data, DB *secondary);
Yoni Fogel's avatar
Yoni Fogel committed
96
    
97 98
#if NEED_TEST

Rich Prohaska's avatar
Rich Prohaska committed
99
static int env_parse_config_line(DB_ENV* dbenv, char *command, char *value) {
Yoni Fogel's avatar
Yoni Fogel committed
100 101 102
    int r;
    
    if (!strcmp(command, "set_data_dir")) {
103
        r = toku_env_set_data_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
104 105
    }
    else if (!strcmp(command, "set_tmp_dir")) {
106
        r = toku_env_set_tmp_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
107 108
    }
    else if (!strcmp(command, "set_lg_dir")) {
109
        r = toku_env_set_lg_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
110 111 112 113 114 115
    }
    else r = -1;
        
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
116
static int env_read_config(DB_ENV *env) {
117
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    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;
151
    int index;
Yoni Fogel's avatar
Yoni Fogel committed
152 153 154 155 156 157 158
    
    buffersize = 1<<10; //1KB
    linebuffer = toku_malloc(buffersize);
    if (!linebuffer) {
        r = ENOMEM;
        goto cleanup;
    }
159
    for (linenumber = 1; !eof; linenumber++) {
Yoni Fogel's avatar
Yoni Fogel committed
160
        /* Read a single line. */
161
        for (index = 0; TRUE; index++) {
Yoni Fogel's avatar
Yoni Fogel committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            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;
                }
            }
181
            linebuffer[index] = ch;
Yoni Fogel's avatar
Yoni Fogel committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195
        }
        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.
196
        while (isspace(*value) && value < end) value++;
Yoni Fogel's avatar
Yoni Fogel committed
197 198 199 200 201 202 203 204 205
        if (value < end) {
            //Strip trailing spaces.
            temp = end;
            while (isspace(*(temp-1))) temp--;
            //Null terminate value.
            *temp = '\0';
        }
        //Parse the line.
        if (strlen(command) == 0 || command[0] == '#') continue; //Ignore Comments.
Rich Prohaska's avatar
Rich Prohaska committed
206
        r = env_parse_config_line(env, command, value < end ? value : "");
Yoni Fogel's avatar
Yoni Fogel committed
207 208 209 210
        if (r != 0) goto parseerror;
    }
    if (0) {
readerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
211
        toku_ydb_do_error(env, r, "Error reading from DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
212 213 214
    }
    if (0) {
parseerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
215
        toku_ydb_do_error(env, r, "Error parsing DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
216 217 218 219 220 221 222 223
    }
cleanup:
    if (full_name) toku_free(full_name);
    if (linebuffer) toku_free(linebuffer);
    if (fp) r2 = fclose(fp);
    return r ? r : r2;
}

224 225
#endif

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

Rich Prohaska's avatar
Rich Prohaska committed
259
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
260
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
261
    int r;
262
    u_int32_t unused_flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
263

Rich Prohaska's avatar
Rich Prohaska committed
264
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
265
	return toku_ydb_do_error(env, EINVAL, "The environment is already open\n");
266
    }
Yoni Fogel's avatar
Yoni Fogel committed
267

268
    if ((flags & DB_USE_ENVIRON) && (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
269
	return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible flags\n");
270
    }
Yoni Fogel's avatar
Yoni Fogel committed
271 272

    if (home) {
273
        if ((flags & DB_USE_ENVIRON) || (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
274
	    return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible with specifying a home\n");
275
	}
Yoni Fogel's avatar
Yoni Fogel committed
276 277
    }
    else if ((flags & DB_USE_ENVIRON) ||
Yoni Fogel's avatar
Yoni Fogel committed
278 279
             ((flags & DB_USE_ENVIRON_ROOT) && geteuid() == 0)) home = getenv("DB_HOME");

280 281
    unused_flags &= ~DB_USE_ENVIRON & ~DB_USE_ENVIRON_ROOT; 

Yoni Fogel's avatar
Yoni Fogel committed
282
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
283

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
284
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
285
	{
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
286 287
	struct stat buf;
	r = stat(home, &buf);
288
	if (r!=0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
289
	    return toku_ydb_do_error(env, errno, "Error from stat(\"%s\",...)\n", home);
290
	}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
291 292
    }

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
293
    if (!(flags & DB_PRIVATE)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
294
	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
295
    }
296
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
297 298 299

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

318 319 320 321 322 323 324
    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
325
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
326 327
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
328 329 330 331
	assert(env->i->logger);
        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
332
	    toku_ydb_do_error(env, r, "Could not open logger\n");
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
333
	died2:
334
	    toku_logger_close(&env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
335 336
	    goto died1;
	}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
337 338
    }

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    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);
    }

356
    r = toku_brt_create_cachetable(&env->i->cachetable, env->i->cachetable_size, ZERO_LSN, env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
357
    if (r!=0) goto died2;
358 359 360

    toku_logger_set_cachetable(env->i->logger, env->i->cachetable);

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
361 362
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
363

Rich Prohaska's avatar
Rich Prohaska committed
364
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
365
    // Even if the env is panicedk, try to close as much as we can.
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
366
    int is_panicked = toku_env_is_panicked(env);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
367
    int r0=0,r1=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
368
    if (env->i->cachetable)
369
        r0=toku_cachetable_close(&env->i->cachetable);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
370
    if (env->i->logger)
371
        r1=toku_logger_close(&env->i->logger);
Yoni Fogel's avatar
Yoni Fogel committed
372 373 374 375 376 377 378 379
    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);
    }
380 381
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
382 383
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
384
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
385
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
386 387
    toku_free(env->i);
    toku_free(env);
388
    ydb_unref();
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
389 390 391
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
392
    if (is_panicked) return EINVAL;
393
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
394
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
395

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

400
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn __attribute__((__unused__))) {
401
    HANDLE_PANICKED_ENV(env);
402 403
    // 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
404
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
405

Rich Prohaska's avatar
Rich Prohaska committed
406
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
407
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
408 409
    if (ncache != 1)
        return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
410 411 412 413 414
    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
415 416 417
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
418 419
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

Rich Prohaska's avatar
Rich Prohaska committed
420
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
421
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
422 423 424 425 426 427
    *gbytes = env->i->cachetable_size >> 30;
    *bytes = env->i->cachetable_size & ((1<<30)-1);
    *ncache = 1;
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
428
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
429
    toku_ydb_lock(); int r = toku_env_get_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
430 431
}

Rich Prohaska's avatar
Rich Prohaska committed
432 433
#endif

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

Rich Prohaska's avatar
Rich Prohaska committed
473
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
474
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
475
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
476

Rich Prohaska's avatar
Rich Prohaska committed
477
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
478 479 480
    env->i->errfile = errfile;
}

Rich Prohaska's avatar
Rich Prohaska committed
481
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
482
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
483
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
484

Rich Prohaska's avatar
Rich Prohaska committed
485
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
486
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
487 488 489 490 491 492

    u_int32_t change = 0;
    if (flags & DB_AUTO_COMMIT) {
        change |=  DB_AUTO_COMMIT;
        flags  &= ~DB_AUTO_COMMIT;
    }
493
    if (flags != 0 && onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
494
	return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags other than DB_AUTO_COMMIT\n");
495
    }
Yoni Fogel's avatar
Yoni Fogel committed
496 497
    if   (onoff) env->i->open_flags |=  change;
    else         env->i->open_flags &= ~change;
Rich Prohaska's avatar
Rich Prohaska committed
498
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
499
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
500

Rich Prohaska's avatar
Rich Prohaska committed
501
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
502
    HANDLE_PANICKED_ENV(env);
503
    bsize=bsize;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
504
    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
505
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
506

Rich Prohaska's avatar
Rich Prohaska committed
507
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
508
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
509
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
510
	return toku_ydb_do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
511
    }
512 513

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
514 515
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
516
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
517
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
518
	}
519
    }
520 521
    else env->i->lg_dir = NULL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
522
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
523

Rich Prohaska's avatar
Rich Prohaska committed
524
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
525
    HANDLE_PANICKED_ENV(env);
526 527 528 529 530 531
    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
532
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
533

Rich Prohaska's avatar
Rich Prohaska committed
534
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
535
    HANDLE_PANICKED_ENV(env);
536
    detect=detect;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
537
    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
538
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
539

Yoni Fogel's avatar
Yoni Fogel committed
540
static int toku_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Yoni Fogel's avatar
Yoni Fogel committed
541
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
542
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
543
    if (env_opened(dbenv))         { return EINVAL; }
Yoni Fogel's avatar
Yoni Fogel committed
544 545
    r = toku_ltm_set_max_locks(dbenv->i->ltm, max);
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
546 547
}

548
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
549
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Yoni Fogel's avatar
Yoni Fogel committed
550
    return toku_env_set_lk_max_locks(env, lk_max);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
551
}
Rich Prohaska's avatar
Rich Prohaska committed
552 553

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

558 559
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
560
    return toku_ltm_get_max_locks(dbenv->i->ltm, lk_maxp);
561 562 563
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
564
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
565 566 567
}

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
568
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
569 570
}

Yoni Fogel's avatar
Yoni Fogel committed
571
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
572 573
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
574

Rich Prohaska's avatar
Rich Prohaska committed
575
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
576
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
577
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
578
	return toku_ydb_do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
579 580
    }
    if (!tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
581
	return toku_ydb_do_error(env, EINVAL, "Tmp dir bust be non-null\n");
582
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
583 584
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
585
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
586
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
587
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
588

Rich Prohaska's avatar
Rich Prohaska committed
589
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
590 591
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
592
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
593
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
594

595 596
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
597 598
}

Rich Prohaska's avatar
Rich Prohaska committed
599
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
600 601
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
602
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
603 604
}

605
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
606
void toku_default_errcall(const char *errpfx, char *msg) {
607 608
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
609
#else
610
void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
611
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
612 613
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
614
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
615

Rich Prohaska's avatar
Rich Prohaska committed
616
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
617
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
618 619 620
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
621
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
622 623 624
}

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

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
629
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
630 631 632
}

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
633
    toku_ydb_lock(); int r = toku_env_set_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
634 635 636
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
637
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
638 639 640
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
641
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
642 643 644
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
645
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
646 647 648
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
649
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
650 651 652
}

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

656 657 658 659
static int locked_env_get_lg_max(DB_ENV * env, u_int32_t *lg_maxp) {
    toku_ydb_lock(); int r = toku_env_get_lg_max(env, lg_maxp); toku_ydb_unlock(); return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
660
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
661
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
662 663 664
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
665
    toku_ydb_lock(); int r = toku_env_set_tmp_dir(env, tmp_dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
666 667 668
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
669
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
670 671 672
}

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
673
    toku_ydb_lock(); int r = toku_env_txn_checkpoint(env, kbyte, min, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
674 675 676
}

static int locked_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
677
    toku_ydb_lock(); int r = toku_env_txn_stat(env, statp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
678 679 680 681 682
}

static int locked_txn_begin(DB_ENV * env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags);

static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
683 684 685 686 687 688
    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
689
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
690
    result->err = toku_locked_env_err;
Rich Prohaska's avatar
Rich Prohaska committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
    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;
706
    result->get_lg_max = locked_env_get_lg_max;
707
    result->set_lk_max_locks = locked_env_set_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
708
    result->get_lk_max_locks = locked_env_get_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
709
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
710
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
Rich Prohaska's avatar
Rich Prohaska committed
711
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
712
#endif
Rich Prohaska's avatar
Rich Prohaska committed
713
    result->set_lk_detect = locked_env_set_lk_detect;
714
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
715
    result->set_lk_max = locked_env_set_lk_max;
716
#endif
Rich Prohaska's avatar
Rich Prohaska committed
717 718 719
    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
720

721
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
722
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
723
    memset(result->i, 0, sizeof *result->i);
724
    result->i->is_panicked=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
725
    result->i->ref_count = 1;
726 727
    result->i->errcall = 0;
    result->i->errpfx = 0;
728
    result->i->errfile = 0;
Yoni Fogel's avatar
Yoni Fogel committed
729 730 731 732

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
                        toku_malloc, toku_free, toku_realloc);
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
733

734
    {
Yoni Fogel's avatar
Yoni Fogel committed
735 736
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
737 738 739
	assert(result->i->logger);
    }

740
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
741
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755
    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
756 757
}

Rich Prohaska's avatar
Rich Prohaska committed
758
int db_env_create(DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
759
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
760 761
}

Yoni Fogel's avatar
Yoni Fogel committed
762
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
763 764 765
    assert(txn);
    toku_lth* lth = txn->i->lth;

Yoni Fogel's avatar
Yoni Fogel committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779
    int r = 0;
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        int r2;
        while (next) {
            r2 = toku_lt_unlock(next, txn);
            if (r2!=0 && !r) r = r2;
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
        txn->i->lth = NULL;
    }
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
780 781
}

Rich Prohaska's avatar
Rich Prohaska committed
782
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
783
    if (!txn) return EINVAL;
784
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
785
    //toku_ydb_notef("flags=%d\n", flags);
786 787
    int nosync = (flags & DB_TXN_NOSYNC)!=0;
    flags &= ~DB_TXN_NOSYNC;
788 789 790 791 792 793 794 795
    if (flags!=0) {
	if (txn->i) {
	    if (txn->i->tokutxn)
		toku_free(txn->i->tokutxn);
	    toku_free(txn->i);
	}
	toku_free(txn);
	return EINVAL;
796
    }
797 798 799
    int r = toku_logger_commit(txn->i->tokutxn, nosync); // frees the tokutxn
    int r2 = toku_txn_release_locks(txn); // release the locks after the commit (otherwise, what if we abort)
    // the toxutxn is freed, and we must free the rest. */
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
800 801 802
    if (txn->i)
        toku_free(txn->i);
    toku_free(txn);
803
    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
804 805
}

Rich Prohaska's avatar
Rich Prohaska committed
806
static u_int32_t toku_txn_id(DB_TXN * txn) {
807
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
808
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
809
    abort();
Rich Prohaska's avatar
Rich Prohaska committed
810
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
811 812 813 814
}

static TXNID next_txn = 0;

815
static int toku_txn_abort(DB_TXN * txn) {
816
    HANDLE_PANICKED_ENV(txn->mgrp);
817
    int r = toku_logger_abort(txn->i->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
818 819

    toku_txn_release_locks(txn);
820 821 822
    toku_free(txn->i);
    toku_free(txn);
    return r;
823 824
}

Rich Prohaska's avatar
Rich Prohaska committed
825 826 827
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
828
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
829 830 831
}

static u_int32_t locked_txn_id(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
832
    toku_ydb_lock(); u_int32_t r = toku_txn_id(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
833 834 835
}

static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
836
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
837 838 839
}

static int locked_txn_abort(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
840
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
841 842 843
}

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
844
    HANDLE_PANICKED_ENV(env);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
845 846
    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");
847
    flags=flags;
848
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
849 850 851
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
852
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
853
    result->mgrp = env;
Rich Prohaska's avatar
Rich Prohaska committed
854 855 856
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
857
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
858 859 860 861
    if (!result->i) {
        toku_free(result);
        return ENOMEM;
    }
862
    memset(result->i, 0, sizeof *result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
863
    result->i->parent = stxn;
Yoni Fogel's avatar
Yoni Fogel committed
864 865 866 867 868 869 870 871 872 873

    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
874 875 876
    }
    
    r = toku_logger_txn_begin(stxn ? stxn->i->tokutxn : 0, &result->i->tokutxn, next_txn++, env->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
877 878 879 880 881 882
    if (r != 0)
        return r;
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
883
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
884 885
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
886
    return toku_logger_log_commit(txn->i->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
887
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
888
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
889

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
890
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
891
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
892 893
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
    abort();
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
894
    toku_ydb_unlock();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
895 896
}

897 898
static int maybe_do_associate_create (DB_TXN*txn, DB*primary, DB*secondary) {
    DBC *dbc;
899
    int r = toku_db_cursor(secondary, txn, &dbc, 0, 0);
900 901
    if (r!=0) return r;
    DBT key,data;
Rich Prohaska's avatar
Rich Prohaska committed
902
    r = toku_c_get(dbc, &key, &data, DB_FIRST);
903
    {
Rich Prohaska's avatar
Rich Prohaska committed
904
	int r2=toku_c_close(dbc);
905 906 907 908 909
	if (r!=DB_NOTFOUND) {
	    return r2;
	}
    }
    /* Now we know the secondary is empty. */
910
    r = toku_db_cursor(primary, txn, &dbc, 0, 0);
911
    if (r!=0) return r;
Rich Prohaska's avatar
Rich Prohaska committed
912
    for (r = toku_c_get(dbc, &key, &data, DB_FIRST); r==0; r = toku_c_get(dbc, &key, &data, DB_NEXT)) {
913 914
	r = do_associated_inserts(txn, &key, &data, secondary);
	if (r!=0) {
Rich Prohaska's avatar
Rich Prohaska committed
915
	    toku_c_close(dbc);
916 917 918 919 920 921
	    return r;
	}
    }
    return 0;
}

922 923 924
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) {
925 926
    HANDLE_PANICKED_DB(primary);
    HANDLE_PANICKED_DB(secondary);
927 928
    unsigned int brtflags;
    
929 930
    if (secondary->i->primary) return EINVAL; // The secondary already has a primary
    if (primary->i->primary)   return EINVAL; // The primary already has a primary
931 932 933 934 935

    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.

936 937 938 939 940 941 942 943 944 945
    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
946 947
    list_push(&primary->i->associated, &secondary->i->associated);
    secondary->i->primary = primary;
948
    if (flags==DB_CREATE) {
949
	// To do this:  If the secondary is empty, then open a cursor on the primary.  Step through it all, doing the callbacks.
950
	// Then insert each callback result into the secondary.
951
	return maybe_do_associate_create(txn, primary, secondary);
952 953
    }
    return 0;
954 955
}

956
static int toku_db_close(DB * db, u_int32_t flags) {
957 958 959 960 961 962 963 964 965 966 967 968 969 970
    if (db->i->primary==0) {
	// 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);
	}
    }
971
    flags=flags;
972
    int r = toku_close_brt(db->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
973 974
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
975 976 977 978
    if (db->i->lt) {
        r = toku_lt_close(db->i->lt);
        if (r!=0) return r;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
979
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
980 981
    // Even if panicked, let's close as much as we can.
    int is_panicked = toku_env_is_panicked(db->dbenv); 
Rich Prohaska's avatar
Rich Prohaska committed
982
    env_unref(db->dbenv);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
983 984 985 986
    toku_free(db->i->database_name);
    toku_free(db->i->full_fname);
    toku_free(db->i);
    toku_free(db);
987
    ydb_unref();
988
    if (r==0 && is_panicked) return EINVAL;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
989 990 991
    return r;
}

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
992 993 994 995 996 997 998 999 1000
/* 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
1001 1002 1003 1004 1005 1006
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
1007 1008 1009
    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
1010 1011
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1012 1013
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
Yoni Fogel committed
1014 1015
    }
#endif
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1016 1017 1018 1019 1020
    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
1021
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1022 1023
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
Yoni Fogel committed
1024
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1025
    return r; 
Yoni Fogel's avatar
Yoni Fogel committed
1026 1027
}

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
//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;
}

1043
static inline BOOL toku_c_uninitialized(DBC* c) {
Yoni Fogel's avatar
Yoni Fogel committed
1044 1045
    return toku_brt_cursor_uninitialized(c->i->c);
}            
Yoni Fogel's avatar
Yoni Fogel committed
1046 1047 1048

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
1049 1050
    memset(key,  0, sizeof(DBT));
    memset(data, 0, sizeof(DBT));
Yoni Fogel's avatar
Yoni Fogel committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    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
1073 1074 1075 1076 1077 1078 1079
/*
    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.
*/
1080
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1081 1082 1083 1084
    while (txn && txn->i->parent) txn = txn->i->parent;
    return txn;
}

Yoni Fogel's avatar
Yoni Fogel committed
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
static int toku_c_get_pre_lock(DBC* c, DBT* key, DBT* data, u_int32_t* flag,
                               DBT* saved_key, DBT* saved_data) {
    assert(saved_key && saved_data && flag);
    DB* db  = c->dbp;
    if (!db->i->lt) return 0;
    saved_key->data = NULL;
    saved_data->data = NULL;
    DB_TXN* txn = c->i->txn;

    u_int32_t get_flag = get_main_cursor_flag(*flag);
    unsigned int brtflags;
    toku_brt_get_flags(db->i->brt, &brtflags);
    BOOL duplicates = (brtflags & TOKU_DB_DUPSORT) != 0;

    int r = 0;
    switch (get_flag) {
        case (DB_CURRENT):
        case (DB_SET):
        case (DB_FIRST):
        case (DB_LAST): {
            /* The above cases have all their code in toku_c_get_post_lock. */
            break;
        }
        case (DB_GET_BOTH): {
            get_both:
Yoni Fogel's avatar
Yoni Fogel committed
1110 1111
            r = toku_lt_acquire_read_lock(db->i->lt, toku_txn_ancestor(txn),
                                          key, data);
Yoni Fogel's avatar
Yoni Fogel committed
1112 1113 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
            break;
        }
        case (DB_SET_RANGE): {
            r = toku_save_original_data(saved_key, key);
            break;
        }
        case (DB_GET_BOTH_RANGE): {
            if (!duplicates) {
                toku_swap_flag(flag, &get_flag, DB_GET_BOTH); goto get_both; }
            r = toku_save_original_data(saved_data, data);
            break;
        }
        case (DB_NEXT):
        case (DB_NEXT_NODUP): {
            r = toku_uninitialized_swap(c, saved_key, saved_data, flag,
                                        &get_flag, DB_FIRST);
            break;
        }
        case (DB_PREV):
        case (DB_PREV_NODUP): {
            r = toku_uninitialized_swap(c, saved_key, saved_data, flag,
                                        &get_flag, DB_LAST);
            break;
        }
#ifdef DB_PREV_DUP
        case (DB_PREV_DUP):
#endif
        case (DB_NEXT_DUP): {
            if (!duplicates || toku_c_uninitialized(c)) r = EINVAL;
            else r = toku_c_get_current_unconditional(c, saved_key, saved_data);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1142
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        }
        default: {
            //TODO: Output an error.
            r = EINVAL;
            break;
        }
    }
    return r;
}

static int toku_c_get_post_lock(DBC* c, DBT* key, DBT* data, u_int32_t flag,
                                int r_last, DBT* saved_key, DBT* saved_data) {
    assert(saved_key && saved_data);
    DB*     db  = c->dbp;
    if (!db->i->lt) return r_last;
    int r = 0;
    if (r_last && r_last != DB_NOTFOUND && r_last != DB_KEYEMPTY) {
        r = r_last;
        goto cleanup;
    }

    DB_TXN* txn = c->i->txn;
    u_int32_t get_flag = get_main_cursor_flag(flag);
    if (r_last == DB_KEYEMPTY) {
        assert(get_flag == DB_CURRENT);
        return r_last;
    }
    assert(r_last == DB_NOTFOUND || r_last == 0);
    BOOL found = r_last == 0;

    BOOL lock = TRUE;
    const DBT* key_l;
    const DBT* key_r;
    const DBT* data_l;
    const DBT* data_r;
    switch (get_flag) {
        case (DB_CURRENT): {
            /* No locking necessary. You already own a lock by virtue
               of having a cursor pointing to this. */
            lock = FALSE;
            break;
        }
        case (DB_SET): {
            key_l  = key_r = key;
            data_l =                toku_lt_neg_infinity;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
        case (DB_GET_BOTH): {
            /* All done in toku_c_get_pre_lock. */
            lock = FALSE;
            break;
        }
        case (DB_FIRST): {
            key_l  = data_l = toku_lt_neg_infinity;
            key_r  = found ? key  : toku_lt_infinity;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
        case (DB_LAST): {
            key_l  = found ? key  : toku_lt_neg_infinity;
            data_l = found ? data : toku_lt_neg_infinity;
            key_r  = data_r = toku_lt_infinity;
            break;
        }
        case (DB_SET_RANGE): {
            key_l  = saved_key;
            data_l = toku_lt_neg_infinity;
            key_r  = found ? key  : toku_lt_infinity;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
        case (DB_GET_BOTH_RANGE): {
            key_l  = key_r = key;
            data_l = saved_data;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
        case (DB_NEXT):
        case (DB_NEXT_NODUP): {
            assert(!toku_c_uninitialized(c));
            key_l  = saved_key;
            data_l = saved_data;
            key_r  = found ? key  : toku_lt_infinity;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
        case (DB_PREV):
        case (DB_PREV_NODUP): {
            assert(!toku_c_uninitialized(c));
            key_l  = found ? key  : toku_lt_neg_infinity;
            data_l = found ? data : toku_lt_neg_infinity;
            key_r  = saved_key;
            data_r = saved_data;
            break;
        }
        case (DB_NEXT_DUP): {
            assert(!toku_c_uninitialized(c));
            key_l  = key_r = saved_key;
            data_l = saved_data;
            data_r = found ? data : toku_lt_infinity;
            break;
        }
#ifdef DB_PREV_DUP
        case (DB_PREV_DUP): {
            assert(!toku_c_uninitialized(c));
            key_l  = key_r = saved_key;
            data_l = found ? data : toku_lt_neg_infinity;
            data_r = saved_data;
            break;
        }
#endif
        default: {
            r = EINVAL;
            lock = FALSE;
            break;
        }
    }
Yoni Fogel's avatar
Yoni Fogel committed
1261 1262
    if (lock) r = toku_lt_acquire_range_read_lock(db->i->lt,
                                                  toku_txn_ancestor(txn),
Yoni Fogel's avatar
Yoni Fogel committed
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
                                                  key_l, data_l,
                                                  key_r, data_r);
cleanup:
    if (saved_key->data)  toku_free(saved_key->data);
    if (saved_data->data) toku_free(saved_data->data);
    return r ? r : r_last;
}



static int toku_c_get_noassociate(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
    HANDLE_PANICKED_DB(c->dbp);
    DBT saved_key;
    DBT saved_data;

    int r;
    r = toku_c_get_pre_lock(c, key, data, &flag, &saved_key, &saved_data);
    if (r!=0) return r;
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    r = toku_brt_cursor_get(c->i->c, key, data, flag, txn);
    r = toku_c_get_post_lock(c, key, data, flag, r, &saved_key, &saved_data);
    return r;
}

static int toku_c_del_noassociate(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    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
1298
        r = toku_lt_acquire_write_lock(db->i->lt, toku_txn_ancestor(c->i->txn),
Yoni Fogel's avatar
Yoni Fogel committed
1299 1300 1301 1302 1303 1304
                                       &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
1305 1306 1307 1308
    return r;
}

static int toku_save_original_data(DBT* dst, DBT* src) {
1309
    int r;
1310
    
1311 1312 1313
    *dst = *src;
#ifdef DB_DBT_PARTIAL
#error toku_c_pget does not properly handle DB_DBT_PARTIAL
1314
#endif
1315 1316 1317 1318 1319 1320
    //We may use this multiple times, we'll free only once at the end.
    dst->flags = DB_DBT_REALLOC;
    //Not using DB_DBT_USERMEM.
    dst->ulen = 0;
    if (src->size) {
        if (!src->data) return EINVAL;
1321
        dst->data = toku_malloc(src->size);
1322 1323 1324
        if (!dst->data) {
            r = ENOMEM;
            return r;
1325
        }
1326
        memcpy(dst->data, src->data, src->size);
1327
    }
1328
    else dst->data = NULL;
1329 1330
    return 0;
}
1331

Yoni Fogel's avatar
 
Yoni Fogel committed
1332 1333
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
    int r;
1334 1335
    int r2;
    int r3;
1336
    DB *db = c->dbp;
1337
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
 
Yoni Fogel committed
1338
    DB *pdb = db->i->primary;
1339
    
Yoni Fogel's avatar
Yoni Fogel committed
1340 1341 1342 1343
    if (!pdb) return EINVAL;  //c_pget does not work on a primary.
	// 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.
	assert(db->i->brt!=pdb->i->brt); // Make sure they realy are different trees.
    assert(db!=pdb);
Yoni Fogel's avatar
Yoni Fogel committed
1344

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    DBT copied_key;
    DBT copied_pkey;
    DBT copied_data;
    //Store original pointers.
    DBT* o_key = key;
    DBT* o_pkey = pkey;
    DBT* o_data = data;
    //Use copied versions for everything until/if success.
    key  = &copied_key;
    pkey = &copied_pkey;
    data = &copied_data;

Yoni Fogel's avatar
Yoni Fogel committed
1357
    if (0) {
1358
delete_silently_and_retry:
1359
        //Free any old data.
1360 1361 1362
        toku_free(key->data);
        toku_free(pkey->data);
        toku_free(data->data);
Yoni Fogel's avatar
Yoni Fogel committed
1363 1364 1365
        //Silently delete and re-run.
        r = toku_c_del_noassociate(c, 0);
        if (r != 0) return r;
1366
    }
1367 1368 1369 1370 1371
    if (0) {
        died0:
        return r;
    }
    //Need to save all the original data.
Yoni Fogel's avatar
Yoni Fogel committed
1372
    r = toku_save_original_data(&copied_key, o_key);   if (r!=0) goto died0;
1373 1374
    if (0) {
        died1:
1375
        toku_free(key->data);
1376 1377
        goto died0;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1378
    r = toku_save_original_data(&copied_pkey, o_pkey); if (r!=0) goto died1;
1379 1380
    if (0) {
        died2:
1381
        toku_free(pkey->data);
1382 1383
        goto died1;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1384
    r = toku_save_original_data(&copied_data, o_data); if (r!=0) goto died2;
1385 1386
    if (0) {
        died3:
1387
        toku_free(data->data);
1388 1389 1390
        goto died2;
    }

Yoni Fogel's avatar
Yoni Fogel committed
1391
    r = toku_c_get_noassociate(c, key, pkey, flag);
1392
    if (r != 0) goto died3;
Rich Prohaska's avatar
Rich Prohaska committed
1393
    r = toku_db_get(pdb, c->i->txn, pkey, data, 0);
1394
    if (r == DB_NOTFOUND)   goto delete_silently_and_retry;
1395
    if (r != 0) goto died3;
Yoni Fogel's avatar
Yoni Fogel committed
1396
    r = verify_secondary_key(db, pkey, data, key);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1397 1398
    if (r == DB_SECONDARY_BAD) goto delete_silently_and_retry;
    if (r != 0) goto died3;
1399 1400 1401 1402 1403 1404 1405 1406 1407

    //Copy everything and return.
    assert(r==0);

    r  = toku_brt_dbt_set_key(db->i->brt,  o_key,  key->data,  key->size);
    r2 = toku_brt_dbt_set_key(pdb->i->brt, o_pkey, pkey->data, pkey->size);
    r3 = toku_brt_dbt_set_value(pdb->i->brt, o_data, data->data, data->size);

    //Cleanup.
1408 1409 1410
    toku_free(key->data);
    toku_free(pkey->data);
    toku_free(data->data);
1411 1412 1413
    if (r!=0) return r;
    if (r2!=0) return r2;
    return r3;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1414 1415
}

Yoni Fogel's avatar
Yoni Fogel committed
1416
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1417
    DB *db = c->dbp;
1418
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1419 1420
    int r;

Yoni Fogel's avatar
Yoni Fogel committed
1421 1422
    if (db->i->primary==0) {
        r = toku_c_get_noassociate(c, key, data, flag);
Yoni Fogel's avatar
Yoni Fogel committed
1423
    }
Yoni Fogel's avatar
Yoni Fogel committed
1424 1425 1426 1427 1428 1429 1430
    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
1431 1432 1433
        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
1434 1435 1436 1437 1438 1439
        memset(&primary_key, 0, sizeof(primary_key));
        r = toku_c_pget(c, key, &primary_key, data, flag);
    }
    return r;
}

1440
static int toku_c_close(DBC * c) {
1441
    int r = toku_brt_cursor_close(c->i->c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1442 1443
    toku_free(c->i);
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1444 1445 1446
    return r;
}

1447 1448 1449 1450 1451
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
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;
    }

1464
    r = toku_c_get(cursor, &currentkey, &currentval, DB_CURRENT_BINDING);
Rich Prohaska's avatar
Rich Prohaska committed
1465 1466
    if (r != 0) goto finish;
    
1467
    r = toku_db_cursor(cursor->dbp, 0, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    if (r != 0) goto finish;

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

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

Yoni Fogel's avatar
 
Yoni Fogel committed
1494 1495
static int toku_db_get_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
1496
    if (flags!=0 && flags!=DB_GET_BOTH) return EINVAL;
1497

Yoni Fogel's avatar
Yoni Fogel committed
1498
    DBC *dbc;
1499
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
1500 1501 1502 1503 1504
    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;
Yoni Fogel's avatar
 
Yoni Fogel committed
1505 1506 1507 1508
}

static int toku_db_del_noassociate(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
    int r;
1509
    if (flags!=0 && flags!=DB_DELETE_ANY) return EINVAL;
Yoni Fogel's avatar
 
Yoni Fogel committed
1510 1511 1512 1513 1514 1515 1516
    //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;
1517
        toku_free(search_val.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
1518 1519
    } 
    //Do the actual deleting.
Yoni Fogel's avatar
Yoni Fogel committed
1520
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
1521
        r = toku_lt_acquire_range_write_lock(db->i->lt, toku_txn_ancestor(txn),
Yoni Fogel's avatar
Yoni Fogel committed
1522 1523 1524 1525
                                             key, toku_lt_neg_infinity,
                                             key, toku_lt_infinity);
        if (r!=0) return r;
    }
1526
    r = toku_brt_delete(db->i->brt, key, txn ? txn->i->tokutxn : 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
1527 1528 1529
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
1530
static int do_associated_deletes(DB_TXN *txn, DBT *key, DBT *data, DB *secondary) {
1531
    u_int32_t brtflags;
Yoni Fogel's avatar
 
Yoni Fogel committed
1532 1533
    DBT idx;
    memset(&idx, 0, sizeof(idx));
1534
    int r2 = 0;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1535 1536 1537
    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
1538 1539
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1540 1541
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
 
Yoni Fogel committed
1542 1543
    }
#endif
1544 1545
    toku_brt_get_flags(secondary->i->brt, &brtflags);
    if (brtflags & TOKU_DB_DUPSORT) {
1546
        //If the secondary has duplicates we need to use cursor deletes.
1547
        DBC *dbc;
1548
        r = toku_db_cursor(secondary, txn, &dbc, 0, 0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1549
        if (r!=0) goto cursor_cleanup;
1550
        r = toku_c_get_noassociate(dbc, &idx, key, DB_GET_BOTH);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1551
        if (r!=0) goto cursor_cleanup;
1552
        r = toku_c_del_noassociate(dbc, 0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1553
    cursor_cleanup:
Rich Prohaska's avatar
Rich Prohaska committed
1554
        r2 = toku_c_close(dbc);
1555 1556
    } else 
        r = toku_db_del_noassociate(secondary, txn, &idx, DB_DELETE_ANY);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1557
    clean_up:
Yoni Fogel's avatar
 
Yoni Fogel committed
1558
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1559 1560
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
1561
    }
1562 1563
    if (r!=0) return r;
    return r2;
Yoni Fogel's avatar
 
Yoni Fogel committed
1564 1565
}

1566
static int toku_c_del(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
 
Yoni Fogel committed
1567
    int r;
1568
    DB* db = c->dbp;
1569
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
 
Yoni Fogel committed
1570
    
1571
    //It is a primary with secondaries, or is a secondary.
Yoni Fogel's avatar
 
Yoni Fogel committed
1572
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
 
Yoni Fogel committed
1573 1574 1575 1576 1577 1578 1579 1580 1581
        DB* pdb;
        DBT pkey;
        DBT data;
        struct list *h;

        memset(&pkey, 0, sizeof(pkey));
        memset(&data, 0, sizeof(data));
        if (db->i->primary == 0) {
            pdb = db;
Rich Prohaska's avatar
Rich Prohaska committed
1582 1583
            r = toku_c_get(c, &pkey, &data, DB_CURRENT);
        } else {
Yoni Fogel's avatar
 
Yoni Fogel committed
1584
            DBT skey;
Yoni Fogel's avatar
 
Yoni Fogel committed
1585
            pdb = db->i->primary;
Yoni Fogel's avatar
 
Yoni Fogel committed
1586 1587
            memset(&skey, 0, sizeof(skey));
            r = toku_c_pget(c, &skey, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
 
Yoni Fogel committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
        }
        if (r != 0) return r;
        
    	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);
    	    if (r!=0) return r;
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
Yoni Fogel's avatar
 
Yoni Fogel committed
1599 1600
    	    //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
1601 1602 1603
    	    if (r!=0) return r;
    	}
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
1604 1605
    r = toku_c_del_noassociate(c, flags);
    return r;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1606 1607
}

1608
static int toku_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
1609
    DB* db = dbc->dbp;
1610
    HANDLE_PANICKED_DB(db);
1611 1612 1613 1614 1615 1616
    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
1617
    DB_TXN* txn = dbc->i->txn;
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    
    //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) {
1637 1638
                toku_free(key_local.data);
                toku_free(data_local.data);
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
            }
            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
1649 1650 1651 1652 1653 1654 1655 1656 1657
        if (db->i->lt) {
            /* Acquire all write locks before  */
            r = toku_lt_acquire_write_lock(db->i->lt, toku_txn_ancestor(txn),
                                           &key_local, &data_local);
            if (r!=0) goto cleanup;
            r = toku_lt_acquire_write_lock(db->i->lt, toku_txn_ancestor(txn),
                                           &key_local, data);
            if (r!=0) goto cleanup;
        }
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
        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
1674
    //Flags must NOT be 0.
1675 1676
    else return EINVAL;
finish:
Rich Prohaska's avatar
Rich Prohaska committed
1677 1678
    //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.
1679 1680 1681 1682 1683
    if (r!=0) goto cleanup;
    r = toku_c_get(dbc, get_key, get_data, DB_GET_BOTH);
    goto cleanup;
}

Rich Prohaska's avatar
Rich Prohaska committed
1684
static int locked_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1685
    toku_ydb_lock(); int r = toku_c_pget(c, key, pkey, data, flag); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1686 1687 1688
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1689
    toku_ydb_lock(); int r = toku_c_get(c, key, data, flag); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1690 1691 1692
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1693
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1694 1695 1696
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1697
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1698 1699 1700
}

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

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

1708
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
1709
    HANDLE_PANICKED_DB(db);
1710 1711
    if (flags != 0)
        return EINVAL;
1712
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1713 1714 1715
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Rich Prohaska's avatar
Rich Prohaska committed
1716 1717 1718 1719 1720 1721
    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;
1722
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1723
    assert(result->i);
1724
    result->dbp = db;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1725
    result->i->txn = txn;
1726
    int r = toku_brt_cursor(db->i->brt, &result->i->c, is_temporary_cursor);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1727
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1728 1729 1730 1731
    *c = result;
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
1732
static int toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
1733
    HANDLE_PANICKED_DB(db);
1734
    int r;
Yoni Fogel's avatar
 
Yoni Fogel committed
1735

Yoni Fogel's avatar
 
Yoni Fogel committed
1736 1737
    //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
1738 1739
        DB* pdb;
        DBT data;
Yoni Fogel's avatar
 
Yoni Fogel committed
1740 1741
        DBT pkey;
        DBT *pdb_key;
Yoni Fogel's avatar
 
Yoni Fogel committed
1742
        struct list *h;
1743
        u_int32_t brtflags;
Yoni Fogel's avatar
 
Yoni Fogel committed
1744 1745

        memset(&data, 0, sizeof(data));
1746 1747

        toku_brt_get_flags(db->i->brt, &brtflags);
Rich Prohaska's avatar
Rich Prohaska committed
1748
        if (brtflags & TOKU_DB_DUPSORT) {
1749 1750
            int r2;
    	    DBC *dbc;
Yoni Fogel's avatar
Yoni Fogel committed
1751
    	    BOOL found = FALSE;
1752 1753 1754 1755 1756

            /* 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.
1757
            r = toku_db_cursor(db, txn, &dbc, 0, 1);
1758
            if (r!=0) return r;
1759 1760
            r = toku_c_get_noassociate(dbc, key, &data, DB_SET);
            while (r==0) {
Rich Prohaska's avatar
Rich Prohaska committed
1761
                r = toku_c_del(dbc, 0);
Yoni Fogel's avatar
Yoni Fogel committed
1762
                if (r==0) found = TRUE;
1763
                if (r!=0 && r!=DB_KEYEMPTY) break;
1764 1765
                r = toku_c_get_noassociate(dbc, key, &data, DB_NEXT_DUP);
                if (r == DB_NOTFOUND) {
Yoni Fogel's avatar
Yoni Fogel committed
1766 1767
                    //If we deleted at least one we're happy.  Quit out.
                    if (found) r = 0;
1768
                    break;
1769 1770
                }
            }
1771

Rich Prohaska's avatar
Rich Prohaska committed
1772
            r2 = toku_c_close(dbc);
1773 1774 1775 1776
            if (r != 0) return r;
            return r2;
        }

1777 1778 1779 1780 1781 1782 1783 1784
        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
1785 1786
        if (db->i->primary == 0) {
            pdb = db;
Rich Prohaska's avatar
Rich Prohaska committed
1787
            r = toku_db_get(db, txn, key, &data, 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
1788
            pdb_key = key;
Yoni Fogel's avatar
 
Yoni Fogel committed
1789 1790 1791
        }
        else {
            pdb = db->i->primary;
Rich Prohaska's avatar
Rich Prohaska committed
1792
            r = toku_db_pget(db, txn, key, &pkey, &data, 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
1793
            pdb_key = &pkey;
Yoni Fogel's avatar
 
Yoni Fogel committed
1794
        }
1795 1796 1797
        if (r != 0) { 
            cleanup(); return r; 
        }
Yoni Fogel's avatar
 
Yoni Fogel committed
1798 1799 1800
        
    	for (h = list_head(&pdb->i->associated); h != &pdb->i->associated; h = h->next) {
    	    struct __toku_db_internal *dbi = list_struct(h, struct __toku_db_internal, associated);
Yoni Fogel's avatar
 
Yoni Fogel committed
1801 1802
    	    if (dbi->db == db) continue;                  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(txn, pdb_key, &data, dbi->db);
1803 1804 1805
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
 
Yoni Fogel committed
1806 1807 1808
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
Yoni Fogel's avatar
 
Yoni Fogel committed
1809 1810
    	    //Primaries cannot have duplicates, (noncursor) del is safe.
    	    r = toku_db_del_noassociate(pdb, txn, pdb_key, DB_DELETE_ANY);
1811 1812 1813
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
 
Yoni Fogel committed
1814
    	}
1815 1816 1817

        cleanup();

Yoni Fogel's avatar
 
Yoni Fogel committed
1818 1819
    	//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
1820
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
1821
    r = toku_db_del_noassociate(db, txn, key, flags);
Rich Prohaska's avatar
Rich Prohaska committed
1822
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1823
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1824

Rich Prohaska's avatar
Rich Prohaska committed
1825 1826 1827 1828
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

1829
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
1830
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1831
    int r;
1832

Rich Prohaska's avatar
Rich Prohaska committed
1833
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
1834 1835
        return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
1836 1837 1838 1839
    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;
1840
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
1841 1842 1843 1844
    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;
1845 1846 1847
}

static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
1848
    HANDLE_PANICKED_DB(db);
1849
    int r;
1850 1851
    int r2;
    DBC *dbc;
1852 1853
    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
1854
    assert(db->i->brt != db->i->primary->i->brt); // Make sure they realy are different trees.
1855
    assert(db!=db->i->primary);
1856

Rich Prohaska's avatar
Rich Prohaska committed
1857 1858 1859
    if ((db->i->open_flags & DB_THREAD) && (db_thread_need_flags(pkey) || db_thread_need_flags(data)))
        return EINVAL;

1860
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
1861
    if (r!=0) return r;
Rich Prohaska's avatar
Rich Prohaska committed
1862
    r = toku_c_pget(dbc, key, pkey, data, DB_SET);
Yoni Fogel's avatar
Yoni Fogel committed
1863
    if (r==DB_KEYEMPTY) r = DB_NOTFOUND;
Rich Prohaska's avatar
Rich Prohaska committed
1864
    r2 = toku_c_close(dbc);
1865 1866
    if (r!=0) return r;
    return r2;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1867 1868
}

Rich Prohaska's avatar
Rich Prohaska committed
1869
#if 0
1870
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
1871 1872
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1873
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1874
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1875
}
Rich Prohaska's avatar
Rich Prohaska committed
1876
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1877

Yoni Fogel's avatar
Yoni Fogel committed
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
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
1898 1899 1900
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
1901
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1902 1903 1904 1905
        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
1906 1907 1908 1909
        // 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
1910 1911
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1912 1913 1914
    }
}

1915
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel committed
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
    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
1931
                r = errno;
Yoni Fogel's avatar
Yoni Fogel committed
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
                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
1949 1950 1951 1952
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
1953 1954
    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
1955 1956 1957
    return EINVAL;
}

Yoni Fogel's avatar
Yoni Fogel committed
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
    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);
        return 0;
    }
    int r = toku_lth_insert(lth, lt);
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
static void toku_txn_remove_lt(DB_TXN* txn, toku_lock_tree* lt) {
    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);
        toku_lth_delete(lth, lt);
    }
}

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

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1990
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1991
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1992
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
1993 1994 1995
    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
1996
    int is_db_unknown = dbtype == DB_UNKNOWN;
1997
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
1998 1999 2000

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

2002 2003 2004 2005 2006 2007 2008 2009
    /* 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;

2010
    if (db_opened(db))
2011
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
2012 2013 2014
    
    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
2015
    // printf("Full name = %s\n", db->i->full_fname);
Yoni Fogel's avatar
Yoni Fogel committed
2016
    db->i->database_name = toku_strdup(dbname ? dbname : "");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2017 2018 2019 2020
    if (db->i->database_name == 0) {
        r = ENOMEM;
        goto error_cleanup;
    }
2021
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2022 2023 2024
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
2025
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2026
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2027 2028 2029
        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. */
2030 2031
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
2032 2033 2034
                    r = EEXIST;
                    goto error_cleanup;
                }
2035
		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
2036 2037
            }
        } else {
2038
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2039 2040 2041 2042
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2043
    }
2044
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2045 2046 2047

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

Yoni Fogel's avatar
Yoni Fogel committed
2049
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
2050
        r = toku_lt_create(&db->i->lt, db, FALSE,
Yoni Fogel's avatar
Yoni Fogel committed
2051
                           toku_db_lt_panic, db->dbenv->i->ltm,
Yoni Fogel's avatar
Yoni Fogel committed
2052 2053 2054 2055
                           db->i->brt->compare_fun, db->i->brt->dup_compare,
                           toku_malloc, toku_free, toku_realloc);
        if (r!=0) goto error_cleanup;
        r = toku_lt_set_txn_add_lt_callback(db->i->lt, toku_txn_add_lt);
2056
	if (r!=0) fprintf(stderr, "%s:%d r=%d (%s)\n", __FILE__, __LINE__, r, strerror(r));
Yoni Fogel's avatar
Yoni Fogel committed
2057
        assert(r==0);
Yoni Fogel's avatar
Yoni Fogel committed
2058 2059
        r = toku_lt_set_txn_remove_lt_callback(db->i->lt, toku_txn_remove_lt);
        assert(r==0);
Yoni Fogel's avatar
Yoni Fogel committed
2060 2061 2062
    }
        
    
Yoni Fogel's avatar
Yoni Fogel committed
2063

2064
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname, dbname,
2065 2066
		      is_db_create, is_db_excl, is_db_unknown,
		      db->dbenv->i->cachetable,
2067 2068
		      txn ? txn->i->tokutxn : NULL_TXN,
		      db);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2069 2070 2071
    if (r != 0)
        goto error_cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
    if (db->i->lt) {
        unsigned int brtflags;
        BOOL dups;
        /* Whether we have dups is only known starting now. */
        toku_brt_get_flags(db->i->brt, &brtflags);
        dups = (brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP);
        r = toku_lt_set_dups(db->i->lt, dups);
        /* toku_lt_set_dups cannot return an error here. */
        assert(r==0);
    }
Yoni Fogel's avatar
Yoni Fogel committed
2082

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2083
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
 
error_cleanup:
    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
2094 2095 2096 2097
    if (db->i->lt) {
        toku_lt_close(db->i->lt);
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2098
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2099
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2100

2101 2102
static int toku_db_put_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
2103

2104
    unsigned int brtflags;
2105
    r = toku_brt_get_flags(db->i->brt, &brtflags); assert(r == 0);
2106 2107 2108

    /* limit the size of key and data */
    unsigned int nodesize;
2109 2110 2111 2112 2113 2114 2115 2116
    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
2117
            return toku_ydb_do_error(db->dbenv, EINVAL, "The largest key or data item allowed is %d bytes", limit);
2118
    }
2119 2120 2121 2122 2123 2124 2125

    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
2126
        r = toku_db_get_noassociate(db, txn, key, toku_init_dbt(&testfordata), 0);
2127 2128
        if (r == 0)
            return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2129
        if (r != DB_NOTFOUND) return r;
2130 2131 2132 2133
    } else if (flags != 0) {
        /* no other flags are currently supported */
        return EINVAL;
    } else {
2134
        assert(flags == 0);
2135
        if (brtflags & TOKU_DB_DUPSORT) {
2136
#if TDB_EQ_BDB
Yoni Fogel's avatar
Yoni Fogel committed
2137
            r = toku_db_get_noassociate(db, txn, key, data, DB_GET_BOTH);
2138 2139
            if (r == 0)
                return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2140
            if (r != DB_NOTFOUND) return r;
2141
#else
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2142
	    return toku_ydb_do_error(db->dbenv, EINVAL, "Tokudb requires that db->put specify DB_YESOVERWRITE or DB_NOOVERWRITE on DB_DUPSORT databases");
2143
#endif
2144 2145
        }
    }
Yoni Fogel's avatar
Yoni Fogel committed
2146
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2147 2148
        r = toku_lt_acquire_write_lock(db->i->lt, toku_txn_ancestor(txn),
                                       key, data);
Yoni Fogel's avatar
Yoni Fogel committed
2149 2150
        if (r!=0) return r;
    }
2151 2152 2153 2154 2155
    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;
}

2156 2157 2158 2159
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
2160 2161
    if (r==DB_DONOTINDEX) { r = 0; goto clean_up; }
    if (r != 0) goto clean_up;
2162 2163 2164 2165 2166
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
	return EINVAL; // We aren't ready for this
    }
#endif
2167
    r = toku_db_put_noassociate(secondary, txn, &idx, key, DB_YESOVERWRITE);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2168
    clean_up:
2169
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2170 2171
        /* This should be free because idx.data is allocated by the user */
        free(idx.data);
2172 2173 2174 2175
    }
    return r;
}

2176
static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2177
    HANDLE_PANICKED_DB(db);
2178 2179
    int r;

2180
    //Cannot put directly into a secondary.
2181
    if (db->i->primary != 0) return EINVAL;
2182

2183
    r = toku_db_put_noassociate(db, txn, key, data, flags);
2184 2185
    if (r!=0) return r;
    // For each secondary add the relevant records.
Yoni Fogel's avatar
 
Yoni Fogel committed
2186 2187 2188 2189 2190 2191 2192
    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;
2193 2194
    }
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2195
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2196

2197
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
2198
    HANDLE_PANICKED_DB(db);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2199
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2200
    int r2;
Yoni Fogel's avatar
Yoni Fogel committed
2201
    char *full_name;
Yoni Fogel's avatar
Yoni Fogel committed
2202 2203 2204 2205 2206 2207

    //TODO: Verify DB* db not yet opened
    if (dbname) {
        //TODO: Verify the target db is not open
        //TODO: Use master database (instead of manual edit) when implemented.

Rich Prohaska's avatar
Rich Prohaska committed
2208
        if ((r = toku_db_open(db, NULL, fname, dbname, DB_BTREE, 0, 0777)) != 0) goto cleanup;
2209
        r = toku_brt_remove_subdb(db->i->brt, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
2210
cleanup:
Rich Prohaska's avatar
Rich Prohaska committed
2211
        r2 = toku_db_close(db, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2212 2213 2214
        return r ? r : r2;
    }
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
Yoni Fogel's avatar
Yoni Fogel committed
2215 2216 2217
    r = find_db_file(db->dbenv, fname, &full_name);
    if (r!=0) return r;
    assert(full_name);
Rich Prohaska's avatar
Rich Prohaska committed
2218
    r2 = toku_db_close(db, 0);
2219
    if (r == 0 && r2 == 0) {
Yoni Fogel's avatar
Yoni Fogel committed
2220
        if (unlink(full_name) != 0) r = errno;
2221
    }
Yoni Fogel's avatar
Yoni Fogel committed
2222
    toku_free(full_name);
Yoni Fogel's avatar
Yoni Fogel committed
2223
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2224
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2225

2226
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
2227
    HANDLE_PANICKED_DB(db);
2228
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2229 2230
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2231 2232 2233 2234 2235
    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
2236
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2237
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2238

2239
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
2240
    HANDLE_PANICKED_DB(db);
2241
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2242 2243 2244
    return r;
}

2245
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
2246
    HANDLE_PANICKED_DB(db);
2247
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2248 2249 2250
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
2251
static int toku_db_set_flags(DB *db, u_int32_t flags) {
2252
    HANDLE_PANICKED_DB(db);
2253

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

Yoni Fogel's avatar
Yoni Fogel committed
2257 2258 2259 2260
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
2261 2262 2263 2264
    if (flags & DB_DUP)
        tflags += TOKU_DB_DUP;
    if (flags & DB_DUPSORT)
        tflags += TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
2265
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2266 2267 2268
    return r;
}

2269
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
2270
    HANDLE_PANICKED_DB(db);
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
    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;
}

2289
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
2290
    HANDLE_PANICKED_DB(db);
2291
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2292
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2293
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2294

Rich Prohaska's avatar
Rich Prohaska committed
2295
#if 0
2296
static int toku_db_stat(DB * db, void *v, u_int32_t flags) {
2297 2298
    HANDLE_PANICKED_DB(db);
    v=v; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2299
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2300 2301
    abort();
}
Rich Prohaska's avatar
Rich Prohaska committed
2302
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2303

Rich Prohaska's avatar
Rich Prohaska committed
2304 2305 2306 2307 2308 2309
static int toku_db_fd(DB *db, int *fdp) {
    HANDLE_PANICKED_DB(db);
    if (!db_opened(db)) return EINVAL;
    return toku_brt_get_fd(db->i->brt, fdp);
}

Yoni Fogel's avatar
Yoni Fogel committed
2310 2311 2312
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
2313
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
                                            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;
}

2329
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
2330 2331 2332 2333 2334 2335
    if (!changed) return r;
    if (r==0) return toku_txn_commit(txn, 0);
    toku_txn_abort(txn);
    return r; 
}

2336
static inline int autotxn_db_associate(DB *primary, DB_TXN *txn, DB *secondary,
Yoni Fogel's avatar
Yoni Fogel committed
2337 2338 2339 2340 2341 2342 2343 2344
                                       int (*callback)(DB *secondary, const DBT *key, const DBT *data, DBT *result), u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(primary, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_associate(primary, txn, secondary, callback, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

Rich Prohaska's avatar
Rich Prohaska committed
2345 2346
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
2347
    toku_ydb_lock(); int r = autotxn_db_associate(primary, txn, secondary, callback, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2348 2349 2350
}

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

2354
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
2355
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2356
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
2357 2358
              "Cursors in a transaction environment must have transactions.\n");
    }
2359
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2360 2361
}

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

2366
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
2367 2368 2369 2370 2371 2372 2373 2374
                                 u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_del(db, txn, key, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

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

2379
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2380 2381 2382 2383 2384 2385
                                 u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_get(db, txn, key, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
2386 2387 2388
}

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
2389
    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
2390 2391
}

2392
static inline int autotxn_db_pget(DB* db, DB_TXN* txn, DBT* key, DBT* pkey,
Yoni Fogel's avatar
Yoni Fogel committed
2393 2394 2395 2396 2397 2398
                                  DBT* data, u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_pget(db, txn, key, pkey, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
2399 2400 2401
}

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
2402
    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
2403 2404
}

2405
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
2406 2407 2408 2409 2410
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, flags & DB_AUTO_COMMIT);
    if (r!=0) return r;
    r = toku_db_open(db, txn, fname, dbname, dbtype, flags & ~DB_AUTO_COMMIT, mode);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
2411 2412 2413
}

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
2414
    toku_ydb_lock(); int r = autotxn_db_open(db, txn, fname, dbname, dbtype, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2415 2416
}

2417
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2418 2419 2420 2421 2422 2423 2424 2425
                                 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_put(db, txn, key, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

Rich Prohaska's avatar
Rich Prohaska committed
2426
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
2427
    toku_ydb_lock(); int r = autotxn_db_put(db, txn, key, data, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2428 2429 2430
}

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

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
2435
    toku_ydb_lock(); int r = toku_db_rename(db, namea, nameb, namec, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2436 2437 2438
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2439
    toku_ydb_lock(); int r = toku_db_set_bt_compare(db, bt_compare); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2440 2441 2442
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2443
    toku_ydb_lock(); int r = toku_db_set_dup_compare(db, dup_compare); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2444 2445 2446 2447 2448 2449 2450
}

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
2451
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2452 2453 2454
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2455
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2456 2457 2458
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2459
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2460 2461 2462
}

static int locked_db_fd(DB *db, int *fdp) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2463
    toku_ydb_lock(); int r = toku_db_fd(db, fdp); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2464 2465 2466
}

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

2469 2470
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2471 2472 2473
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
Rich Prohaska's avatar
Rich Prohaska committed
2474
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2475
            return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
2476
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2477
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
2478
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2479 2480
        if (r != 0)
            return r;
Rich Prohaska's avatar
Rich Prohaska committed
2481
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2482
        if (r != 0) {
Rich Prohaska's avatar
Rich Prohaska committed
2483
            toku_env_close(env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2484 2485
            return r;
        }
Rich Prohaska's avatar
Rich Prohaska committed
2486
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2487
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2488
    
2489
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2490
    if (result == 0) {
Rich Prohaska's avatar
Rich Prohaska committed
2491
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2492
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2493
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2494 2495
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Rich Prohaska's avatar
Rich Prohaska committed
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
    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;
2515
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2516 2517
    if (result->i == 0) {
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
2518
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2519 2520 2521
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
2522
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2523 2524 2525 2526 2527 2528 2529 2530
    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;
2531 2532 2533
    list_init(&result->i->associated);
    result->i->primary = 0;
    result->i->associate_callback = 0;
2534
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2535 2536 2537
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
2538
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2539 2540
        return ENOMEM;
    }
2541
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2542 2543
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2544
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2545

Rich Prohaska's avatar
Rich Prohaska committed
2546
int db_create(DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2547
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2548 2549 2550 2551
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2552 2553 2554 2555 2556 2557 2558 2559
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
2560 2561 2562 2563
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }

Rich Prohaska's avatar
Rich Prohaska committed
2564
    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
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
    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
2577 2578
    return DB_VERSION_STRING;
}
2579 2580 2581 2582
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}