ydb.c 95.9 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

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

24
#include "toku_assert.h"
25
#include "ydb-internal.h"
26
#include "brt-internal.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
27
#include "cachetable.h"
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
28 29
#include "log.h"
#include "memory.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
30

31 32 33 34 35 36 37 38 39 40
#ifdef TOKUTRACE
 #define DB_ENV_CREATE_FUN db_env_create_toku10
 #define DB_CREATE_FUN db_create_toku10
#else
 #define DB_ENV_CREATE_FUN db_env_create
 #define DB_CREATE_FUN db_create
 int toku_set_trace_file (char *fname __attribute__((__unused__))) { return 0; }
 int toku_close_trace_file (void) { return 0; } 
#endif

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
41 42
/** The default maximum number of persistent locks in a lock tree  */
const u_int32_t __toku_env_default_max_locks = 1000;
Rich Prohaska's avatar
Rich Prohaska committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

/* the ydb reference is used to cleanup the library when there are no more references to it */
static int toku_ydb_refs = 0;

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

static inline void ydb_unref() {
    assert(toku_ydb_refs > 0);
    if (--toku_ydb_refs == 0) {
        /* call global destructors */
        toku_malloc_cleanup();
    }
}

/* env methods */
static int toku_env_close(DB_ENV *env, u_int32_t flags);
61 62 63
static int toku_env_set_data_dir(DB_ENV * env, const char *dir);
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir);
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir);
Rich Prohaska's avatar
Rich Prohaska committed
64 65

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

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

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


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

static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags);
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags);
static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags);
88
static int toku_db_cursor(DB *db, DB_TXN * txn, DBC **c, u_int32_t flags, int is_temporary_cursor);
Rich Prohaska's avatar
Rich Prohaska committed
89 90 91 92 93 94 95 96 97 98

/* txn methods */

/* cursor methods */
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag);
static int toku_c_get_noassociate(DBC * c, DBT * key, DBT * data, u_int32_t flag);
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag);
static int toku_c_del(DBC *c, u_int32_t flags);
static int toku_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags);
static int toku_c_close(DBC * c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
99

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

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

Rich Prohaska's avatar
Rich Prohaska committed
123
static int env_read_config(DB_ENV *env) {
124
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    const char* config_name = "DB_CONFIG";
    char* full_name = NULL;
    char* linebuffer = NULL;
    int buffersize;
    FILE* fp = NULL;
    int r = 0;
    int r2 = 0;
    char* command;
    char* value;
    
    full_name = construct_full_name(env->i->dir, config_name);
    if (full_name == 0) {
        r = ENOMEM;
        goto cleanup;
    }
    if ((fp = fopen(full_name, "r")) == NULL) {
        //Config file is optional.
        if (errno == ENOENT) {
            r = EXIT_SUCCESS;
            goto cleanup;
        }
        r = errno;
        goto cleanup;
    }
    //Read each line, applying configuration parameters.
    //After ignoring leading white space, skip any blank lines
    //or comments (starts with #)
    //Command contains no white space.  Value may contain whitespace.
    int linenumber;
    int ch = '\0';
    BOOL eof = FALSE;
    char* temp;
    char* end;
158
    int index;
Yoni Fogel's avatar
Yoni Fogel committed
159 160 161 162 163 164 165
    
    buffersize = 1<<10; //1KB
    linebuffer = toku_malloc(buffersize);
    if (!linebuffer) {
        r = ENOMEM;
        goto cleanup;
    }
166
    for (linenumber = 1; !eof; linenumber++) {
Yoni Fogel's avatar
Yoni Fogel committed
167
        /* Read a single line. */
168
        for (index = 0; TRUE; index++) {
Yoni Fogel's avatar
Yoni Fogel committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
            if ((ch = getc(fp)) == EOF) {
                eof = TRUE;
                if (ferror(fp)) {
                    /* Throw away current line and print warning. */
                    r = errno;
                    goto readerror;
                }
                break;
            }
            if (ch == '\n') break;
            if (index + 1 >= buffersize) {
                //Double the buffer.
                buffersize *= 2;
                linebuffer = toku_realloc(linebuffer, buffersize);
                if (!linebuffer) {
                    r = ENOMEM;
                    goto cleanup;
                }
            }
188
            linebuffer[index] = ch;
Yoni Fogel's avatar
Yoni Fogel committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202
        }
        linebuffer[index] = '\0';
        end = &linebuffer[index];

        /* Separate the line into command/value */
        command = linebuffer;
        //Strip leading spaces.
        while (isspace(*command) && command < end) command++;
        //Find end of command.
        temp = command;
        while (!isspace(*temp) && temp < end) temp++;
        *temp++ = '\0'; //Null terminate command.
        value = temp;
        //Strip leading spaces.
203
        while (isspace(*value) && value < end) value++;
Yoni Fogel's avatar
Yoni Fogel committed
204 205 206 207 208 209 210 211 212
        if (value < end) {
            //Strip trailing spaces.
            temp = end;
            while (isspace(*(temp-1))) temp--;
            //Null terminate value.
            *temp = '\0';
        }
        //Parse the line.
        if (strlen(command) == 0 || command[0] == '#') continue; //Ignore Comments.
Rich Prohaska's avatar
Rich Prohaska committed
213
        r = env_parse_config_line(env, command, value < end ? value : "");
Yoni Fogel's avatar
Yoni Fogel committed
214 215 216 217
        if (r != 0) goto parseerror;
    }
    if (0) {
readerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
218
        toku_ydb_do_error(env, r, "Error reading from DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
219 220 221
    }
    if (0) {
parseerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
222
        toku_ydb_do_error(env, r, "Error parsing DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
223 224 225 226 227 228 229 230
    }
cleanup:
    if (full_name) toku_free(full_name);
    if (linebuffer) toku_free(linebuffer);
    if (fp) r2 = fclose(fp);
    return r ? r : r2;
}

231 232
#endif

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

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

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

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

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

287 288
    unused_flags &= ~DB_USE_ENVIRON & ~DB_USE_ENVIRON_ROOT; 

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

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

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
300
    if (!(flags & DB_PRIVATE)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
301
	return toku_ydb_do_error(env, EINVAL, "TokuDB requires DB_PRIVATE when opening an env\n");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
302
    }
303
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
304 305 306

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

325 326 327 328 329 330 331
    unused_flags &= ~DB_INIT_TXN & ~DB_INIT_LOG; 

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

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
332
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
333 334
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
335 336 337 338
	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
339
	    toku_ydb_do_error(env, r, "Could not open logger\n");
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
340
	died2:
341
	    toku_logger_close(&env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
342 343
	    goto died1;
	}
344 345 346
    } else {
	r = toku_logger_close(&env->i->logger); // if no logging system, then kill the logger
	assert(r==0);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
347 348
    }

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

366
    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
367
    if (r!=0) goto died2;
368

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

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

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

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

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

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

Rich Prohaska's avatar
Rich Prohaska committed
430
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
431
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
432 433 434 435 436 437
    *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
438
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
439
    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
440 441
}

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

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

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

Rich Prohaska's avatar
Rich Prohaska committed
487
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
488 489 490
    env->i->errfile = errfile;
}

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

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

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

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

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

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
524 525
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
526
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
527
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
528
	}
529
    }
530 531
    else env->i->lg_dir = NULL;
    return 0;
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_lg_max(DB_ENV * env, u_int32_t lg_max) {
535
    HANDLE_PANICKED_ENV(env);
536 537 538 539 540 541
    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
542
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
543

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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
643
    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
644 645 646
}

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

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

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

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

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

666 667 668 669
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
670
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
671
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
672 673 674
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
675
    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
676 677 678
}

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

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
683
    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
684 685 686
}

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

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

Yoni Fogel's avatar
Yoni Fogel committed
692 693 694 695 696 697
static int toku_db_lt_panic(DB* db, int r);

static toku_dbt_cmp toku_db_get_compare_fun(DB* db);

static toku_dbt_cmp toku_db_get_dup_compare(DB* db);

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

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

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
747 748 749
                         toku_db_lt_panic, 
                         toku_db_get_compare_fun, toku_db_get_dup_compare, 
                         toku_malloc, toku_free, toku_realloc);
Yoni Fogel's avatar
Yoni Fogel committed
750
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
751

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

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

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

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

Yoni Fogel's avatar
Yoni Fogel committed
784 785
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
786 787 788 789
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
Yoni Fogel's avatar
Yoni Fogel committed
790 791 792 793 794 795
            r = toku_lt_unlock(next, toku_txn_get_txnid(txn->i->tokutxn));
            if (!first_error && r!=0) { first_error = r; }
            if (r == 0) {
                r = toku_lt_remove_ref(next);
                if (!first_error && r!=0) { first_error = r; }
            }
Yoni Fogel's avatar
Yoni Fogel committed
796 797 798 799 800
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
        txn->i->lth = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
801 802
    r = first_error;

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

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

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

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

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

Rich Prohaska's avatar
Rich Prohaska committed
848 849 850
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
851
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
852 853 854
}

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

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

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

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

    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
897 898
    }
    
899
    r = toku_logger_txn_begin(stxn ? stxn->i->tokutxn : 0, &result->i->tokutxn, env->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
900 901 902 903 904 905
    if (r != 0)
        return r;
    *txn = result;
    return 0;
}

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

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

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

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

    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.

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

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

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

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
//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;
}

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

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
1074 1075
    memset(key,  0, sizeof(DBT));
    memset(data, 0, sizeof(DBT));
Yoni Fogel's avatar
Yoni Fogel committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    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
1098 1099 1100 1101 1102 1103 1104
/*
    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.
*/
1105
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1106
    while (txn && txn->i->parent) txn = txn->i->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1107

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

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

Yoni Fogel's avatar
Yoni Fogel committed
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 1142 1143 1144 1145
/* c_get has many subfunctions with lots of parameters
 * this structure exists to simplify it. */
typedef struct {
    DBC*        c;                  // The cursor
    DB*         db;                 // db the cursor is iterating over
    DB_TXN*     txn_anc;            // The (root) ancestor of the transaction
    TXNID       id_anc;
    DBT         cursor_key;         // Original position of cursor (key portion)
    DBT         cursor_val;         // Original position of cursor (val portion)
    DBT         tmp_key;            // Temporary key to protect out param
    DBT         tmp_val;            // Temporary val to protect out param
    DBT         tmp_dat;            // Temporary data val to protect out param 
    u_int32_t   flag;               // The c_get flag
    u_int32_t   op;                 // The operation portion of the c_get flag
    BOOL        cursor_is_write;    // Whether op can change position of cursor
    BOOL        cursor_was_saved;   // Whether we saved the cursor yet.
    BOOL        key_is_read;        
    BOOL        key_is_write;
    BOOL        val_is_read;
    BOOL        val_is_write;
    BOOL        dat_is_read;
    BOOL        dat_is_write;
    BOOL        duplicates;
    BOOL        cursor_malloced;
    BOOL        tmp_key_malloced;
    BOOL        tmp_val_malloced;
    BOOL        tmp_dat_malloced;
} C_GET_VARS;

static void toku_c_get_fix_flags(C_GET_VARS* g) {
    g->op = get_main_cursor_flag(g->flag);

    switch (g->op) {
Yoni Fogel's avatar
Yoni Fogel committed
1146 1147
        case DB_NEXT:
        case DB_NEXT_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1148 1149 1150
            if (toku_c_uninitialized(g->c)) toku_swap_flag(&g->flag, &g->op, DB_FIRST);
            else if (!g->duplicates && g->op == DB_NEXT) {
                toku_swap_flag(&g->flag, &g->op, DB_NEXT_NODUP);
Yoni Fogel's avatar
Yoni Fogel committed
1151 1152
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1153 1154
        case DB_PREV:
        case DB_PREV_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1155 1156 1157
            if (toku_c_uninitialized(g->c)) toku_swap_flag(&g->flag, &g->op, DB_LAST);
            else if (!g->duplicates && g->op == DB_PREV) {    
                toku_swap_flag(&g->flag, &g->op, DB_PREV_NODUP);
Yoni Fogel's avatar
Yoni Fogel committed
1158 1159
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1160
        case DB_GET_BOTH_RANGE:
Yoni Fogel's avatar
Yoni Fogel committed
1161 1162
            if (!g->duplicates) {
                toku_swap_flag(&g->flag, &g->op, DB_GET_BOTH);
Yoni Fogel's avatar
Yoni Fogel committed
1163 1164
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1165
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1166 1167 1168 1169
            break;
    }
}

Yoni Fogel's avatar
Yoni Fogel committed
1170 1171 1172 1173
static inline void toku_c_pget_fix_flags(C_GET_VARS* g) {
    toku_c_get_fix_flags(g);
}

Yoni Fogel's avatar
Yoni Fogel committed
1174 1175 1176 1177
static int toku_c_get_pre_acquire_lock_if_possible(C_GET_VARS* g, DBT* key, DBT* data) {
    int r = ENOSYS;
    toku_lock_tree* lt = g->db->i->lt;
    if (!lt) { r = 0; goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
1178

Yoni Fogel's avatar
Yoni Fogel committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    /* We know what to lock ahead of time. */
    if (g->op == DB_GET_BOTH ||
        (g->op == DB_SET && !g->duplicates)) {
        r = toku_txn_add_lt(g->txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_read_lock(lt, g->db, g->id_anc, key, data);
        if (r!=0) goto cleanup;
    }
    r = 0;
cleanup:
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1191

Yoni Fogel's avatar
Yoni Fogel committed
1192 1193
static int toku_c_get_describe_inputs(C_GET_VARS* g) { 
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
1194 1195 1196
    /* Default for (key|value)_is_(read|write) is FALSE.
     * Default for cursor_is_write is TRUE. */
    g->cursor_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1197 1198 1199 1200
    switch (g->op) {
        case DB_SET:
            g->key_is_read  = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1201
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1202 1203 1204 1205
        case DB_SET_RANGE:
            g->key_is_read  = TRUE;
            g->key_is_write = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1206
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1207 1208 1209
        case DB_GET_BOTH:
            g->key_is_read  = TRUE;
            g->val_is_read  = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1210
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1211 1212 1213 1214 1215
        case DB_GET_BOTH_RANGE:
            assert(g->duplicates);
            g->key_is_read  = TRUE;
            g->val_is_read  = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1216
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1217
        case DB_CURRENT:
Yoni Fogel's avatar
Yoni Fogel committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
        case DB_CURRENT_BINDING:
            /* Cursor does not change. */
            g->cursor_is_write = FALSE;
            /* Break through to next case on purpose. */
        case DB_NEXT_DUP:
#if defined(DB_PREV_DUP)
        case DB_PREV_DUP:
#endif
            if (toku_c_uninitialized(g->c)) {
               r = EINVAL; goto cleanup;
            }
            /* Break through to next case on purpose. */
Yoni Fogel's avatar
Yoni Fogel committed
1230 1231 1232 1233 1234 1235 1236 1237
        case DB_FIRST:
        case DB_LAST:
        case DB_NEXT:
        case DB_NEXT_NODUP:
        case DB_PREV:
        case DB_PREV_NODUP:
            g->key_is_write = TRUE;
            g->val_is_write = TRUE;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1238
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1239
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1240
            r = EINVAL;
Yoni Fogel's avatar
Yoni Fogel committed
1241
            goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1242
    }
Yoni Fogel's avatar
Yoni Fogel committed
1243 1244
    r = 0;
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
1245 1246 1247
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1248 1249 1250 1251 1252 1253
static int toku_c_pget_describe_inputs(C_GET_VARS* g) {
    int r = toku_c_get_describe_inputs(g);
    g->dat_is_read  = FALSE;
    g->dat_is_write = TRUE;
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1254

Yoni Fogel's avatar
Yoni Fogel committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
static int toku_c_pget_save_inputs(C_GET_VARS* g, DBT* key, DBT* val, DBT* dat) {
    int r = ENOSYS;

    /* 
     * Readonly:  Copy original struct
     * Writeonly: Set to 0 (already done), DB_DBT_REALLOC, copy back later.
     * ReadWrite: Make a copy of original in new memory, copy back later
     * */
    if (key) {
        assert(g->key_is_read || g->key_is_write);
        if (g->key_is_read && !g->key_is_write) g->tmp_key = *key;
        else {
            /* g->key_is_write */
            g->tmp_key.flags = DB_DBT_REALLOC;
            if (g->key_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_key, key))) goto cleanup;
            g->tmp_key_malloced = TRUE;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1273
    }
Yoni Fogel's avatar
Yoni Fogel committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    if (val) {
        assert(g->val_is_read || g->val_is_write);
        if (g->val_is_read && !g->val_is_write) g->tmp_val = *val;
        else {
            /* g->val_is_write */
            g->tmp_val.flags = DB_DBT_REALLOC;
            if (g->val_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_val, val))) goto cleanup;
            g->tmp_val_malloced = TRUE;
        }
    }
    if (dat) {
        assert(g->dat_is_read || g->dat_is_write);
        if (g->dat_is_read && !g->dat_is_write) g->tmp_dat = *dat;
        else {
            /* g->dat_is_write */
            g->tmp_dat.flags = DB_DBT_REALLOC;
            if (g->dat_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_dat, dat))) goto cleanup;
            g->tmp_dat_malloced = TRUE;
        }
    }
    r = 0;
cleanup:
    if (r!=0) {
        /* Cleanup memory allocated if necessary. */
        if (g->tmp_key.data && g->tmp_key_malloced) toku_free(g->tmp_key.data);
        if (g->tmp_val.data && g->tmp_val_malloced) toku_free(g->tmp_val.data);
        if (g->tmp_dat.data && g->tmp_dat_malloced) toku_free(g->tmp_dat.data);                
    }
    return r;
}

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

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

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

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

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

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

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

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

Yoni Fogel's avatar
Yoni Fogel committed
1441 1442
    r = toku_brt_cursor_copyout_with_dat(g->c->i->c, write_key, write_val,
                                         primary,    write_dat, &g->tmp_dat);
Yoni Fogel's avatar
Yoni Fogel committed
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
    return r;
}

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

Yoni Fogel's avatar
Yoni Fogel committed
1454
    r = toku_brt_cursor_copyout(g->c->i->c, write_key, write_val);
Yoni Fogel's avatar
Yoni Fogel committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
    return r;
}

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

    /* Standardize the op flag. */
    toku_c_get_fix_flags(&g);
    /* If we know what to lock before the cursor op, lock now. */
    if ((r = toku_c_get_pre_acquire_lock_if_possible(&g, key, val))) goto cleanup;
    /* Determine whether the key and val parameters are read, write,
     * or both. */
    if ((r = toku_c_get_describe_inputs(&g))) goto cleanup;
    /* Save the cursor position if the op can modify the cursor position. */
    if ((r = toku_c_get_save_cursor(&g))) goto cleanup;
    /* Save key and value to temporary local versions. */
    if ((r = toku_c_get_save_inputs(&g, key, val))) goto cleanup;
    /* Run the cursor operation on the brt. */
Yoni Fogel's avatar
Yoni Fogel committed
1491
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    r_cursor_op = r = toku_brt_cursor_get(c->i->c, &g.tmp_key, &g.tmp_val, g.flag, txn);
    /* Only DB_CURRENT should possibly retun DB_KEYEMPTY,
     * and DB_CURRENT requires no locking. */
    if (r==DB_KEYEMPTY) { assert(g.op==DB_CURRENT); goto cleanup; }
    /* If we do not find what the query wants, a lock can still fail
     * 'first'. */
    if (r!=0 && r!=DB_NOTFOUND) goto cleanup;
    /* If we have not yet locked, lock now. */
    BOOL found = r_cursor_op==0;
    r = toku_c_get_post_lock(&g, found, key, val);
    if (r!=0) goto cleanup;
    /* if found, write the outputs to the output parameters. */
    if (found && (r = toku_c_get_assign_outputs(&g, key, val))) goto cleanup; 
    r = r_cursor_op;
cleanup:
    if (g.cursor_was_saved && g.cursor_malloced) {
        /* We saved the cursor.  We either need to restore it, or free
         * the saved version. */
        if (r!=0 && r!=DB_NOTFOUND) {
            /* Failure since 0 and DB_NOTFOUND are 'successes';
             * Restore the cursor. */
            brt_cursor_set_key_val_manually(c->i->c, &g.cursor_key, &g.cursor_val);
            /* cursor_key/val will be zeroed out. */
        }
        else {
            /* Delete the saved cursor. */
            if (g.cursor_key.data) toku_free(g.cursor_key.data);
            if (g.cursor_val.data) toku_free(g.cursor_val.data);
        }
    }
    /* Cleanup temporary keys. */
    if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);
    if (g.tmp_val.data && g.tmp_val_malloced) toku_free(g.tmp_val.data);
Yoni Fogel's avatar
Yoni Fogel committed
1525 1526 1527 1528
    return r;
}

static int toku_c_del_noassociate(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    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
1539 1540 1541 1542 1543
        DB_TXN* txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, db->i->lt);
        if (r!=0) { return r; }
        TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
        r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
1544 1545 1546 1547 1548 1549
                                       &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
1550 1551 1552
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
1553
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Yoni Fogel's avatar
Yoni Fogel committed
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
    HANDLE_PANICKED_DB(c->dbp);
    DB *pdb = c->dbp->i->primary;
    /* c_pget does not work on a primary. */
    if (!pdb) return EINVAL;

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

Yoni Fogel's avatar
 
Yoni Fogel committed
1567
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    C_GET_VARS g;
    memset(&g, 0, sizeof(g));
    /* Initialize variables. */
    g.c    = c;
    g.db   = c->dbp;
    g.flag = flag;
    unsigned int brtflags;
    toku_brt_get_flags(g.db->i->brt, &brtflags);
    g.duplicates   = (brtflags & TOKU_DB_DUPSORT) != 0;

    /* Standardize the op flag. */
Yoni Fogel's avatar
Yoni Fogel committed
1579
    toku_c_pget_fix_flags(&g);
Yoni Fogel's avatar
Yoni Fogel committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    /* Determine whether the key, val, and data, parameters are read, write,
     * or both. */
    if ((r = toku_c_pget_describe_inputs(&g))) goto cleanup;
 
    /* The 'key' from C_GET_VARS is the secondary key, and the 'val'
     * from C_GET_VARS is the primary key.  The 'data' parameter here
     * is ALWAYS write-only */ 

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

Yoni Fogel's avatar
Yoni Fogel committed
1591
    if (0) {
1592
delete_silently_and_retry:
Yoni Fogel's avatar
Yoni Fogel committed
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        /* Free all old 'saved' elements, return to pristine state. */
        if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);                
        memset(&g.tmp_key, 0, sizeof(g.tmp_key));
        g.tmp_key_malloced = FALSE;

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

        if (g.tmp_dat.data && g.tmp_dat_malloced) toku_free(g.tmp_dat.data);                
        memset(&g.tmp_dat, 0, sizeof(g.tmp_dat));
        g.tmp_dat_malloced = FALSE;
        /* Silently delete and re-run. */
        if ((r = toku_c_del_noassociate(c, 0))) goto cleanup;
1607
    }
Yoni Fogel's avatar
Yoni Fogel committed
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    /* Save the inputs. */
    if ((r = toku_c_pget_save_inputs(&g, key, pkey, data))) goto cleanup;

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

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

    r = verify_secondary_key(g.db, &g.tmp_val, &g.tmp_dat, &g.tmp_key);
    if (r==DB_SECONDARY_BAD) goto delete_silently_and_retry;
    if (r!=0) goto cleanup;

    /* Atomically assign all 3 outputs. */
    if ((r = toku_c_pget_assign_outputs(&g, key, pkey, data))) goto cleanup;
    r = 0;
cleanup:
    if (g.cursor_was_saved && g.cursor_malloced) {
        /* We saved the cursor.  We either need to restore it, or free
         * the saved version. */
        if (r!=0) {
            /* Restore the cursor. */
            brt_cursor_set_key_val_manually(c->i->c, &g.cursor_key, &g.cursor_val);
            /* cursor_key/val will be zeroed out. */
        }
        else {
            /* Delete the saved cursor. */
            if (g.cursor_key.data) toku_free(g.cursor_key.data);
            if (g.cursor_val.data) toku_free(g.cursor_val.data);
        }
1638
    }
Yoni Fogel's avatar
Yoni Fogel committed
1639 1640 1641 1642 1643
    /* Cleanup temporary keys. */
    if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);
    if (g.tmp_val.data && g.tmp_val_malloced) toku_free(g.tmp_val.data);
    if (g.tmp_dat.data && g.tmp_dat_malloced) toku_free(g.tmp_dat.data);                
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1644 1645
}

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

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

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

1677 1678 1679 1680 1681
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
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
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;
    }

1694
    r = toku_c_get(cursor, &currentkey, &currentval, DB_CURRENT_BINDING);
Rich Prohaska's avatar
Rich Prohaska committed
1695 1696
    if (r != 0) goto finish;
    
1697
    r = toku_db_cursor(cursor->dbp, 0, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    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
1724 1725
static int toku_db_get_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
1726
    if (flags!=0 && flags!=DB_GET_BOTH) return EINVAL;
1727

Yoni Fogel's avatar
Yoni Fogel committed
1728
    DBC *dbc;
1729
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
1730 1731 1732 1733 1734
    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
1735 1736 1737 1738
}

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

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

1800
static int toku_c_del(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
 
Yoni Fogel committed
1801
    int r;
1802
    DB* db = c->dbp;
1803
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
 
Yoni Fogel committed
1804
    
1805
    //It is a primary with secondaries, or is a secondary.
Yoni Fogel's avatar
 
Yoni Fogel committed
1806
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
 
Yoni Fogel committed
1807 1808 1809 1810 1811 1812 1813
        DB* pdb;
        DBT pkey;
        DBT data;
        struct list *h;

        memset(&pkey, 0, sizeof(pkey));
        memset(&data, 0, sizeof(data));
Yoni Fogel's avatar
Yoni Fogel committed
1814 1815
        pkey.flags = DB_DBT_REALLOC;
        data.flags = DB_DBT_REALLOC;
Yoni Fogel's avatar
 
Yoni Fogel committed
1816 1817
        if (db->i->primary == 0) {
            pdb = db;
Rich Prohaska's avatar
Rich Prohaska committed
1818
            r = toku_c_get(c, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
1819
            if (r != 0) goto assoc_cleanup;
Rich Prohaska's avatar
Rich Prohaska committed
1820
        } else {
Yoni Fogel's avatar
 
Yoni Fogel committed
1821
            DBT skey;
Yoni Fogel's avatar
 
Yoni Fogel committed
1822
            pdb = db->i->primary;
Yoni Fogel's avatar
 
Yoni Fogel committed
1823
            memset(&skey, 0, sizeof(skey));
Yoni Fogel's avatar
Yoni Fogel committed
1824
            skey.flags = DB_DBT_MALLOC;
Yoni Fogel's avatar
 
Yoni Fogel committed
1825
            r = toku_c_pget(c, &skey, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
1826 1827
            if (r!=0) goto assoc_cleanup;
            if (skey.data) toku_free(skey.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
1828 1829 1830 1831 1832 1833
        }
        
    	for (h = list_head(&pdb->i->associated); h != &pdb->i->associated; h = h->next) {
    	    struct __toku_db_internal *dbi = list_struct(h, struct __toku_db_internal, associated);
    	    if (dbi->db == db) continue;  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(c->i->txn, &pkey, &data, dbi->db);
Yoni Fogel's avatar
Yoni Fogel committed
1834
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
1835 1836 1837
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
Yoni Fogel's avatar
 
Yoni Fogel committed
1838 1839
    	    //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
1840
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
1841
    	}
Yoni Fogel's avatar
Yoni Fogel committed
1842 1843 1844 1845
assoc_cleanup:
        if (pkey.data) toku_free(pkey.data);
        if (data.data) toku_free(data.data);
        if (r!=0) goto cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
1846
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
1847
    r = toku_c_del_noassociate(c, flags);
Yoni Fogel's avatar
Yoni Fogel committed
1848 1849 1850
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
Yoni Fogel's avatar
 
Yoni Fogel committed
1851
    return r;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1852 1853
}

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

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1939
    toku_ydb_lock(); int r = toku_c_get(c, key, data, flag); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1940 1941 1942
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1943
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1944 1945 1946
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1947
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1948 1949 1950
}

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

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

1958
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
1959
    HANDLE_PANICKED_DB(db);
1960 1961
    if (flags != 0)
        return EINVAL;
1962
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1963 1964 1965
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Rich Prohaska's avatar
Rich Prohaska committed
1966 1967 1968 1969 1970 1971
    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;
1972
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1973
    assert(result->i);
1974
    result->dbp = db;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1975
    result->i->txn = txn;
1976
    int r = toku_brt_cursor(db->i->brt, &result->i->c, is_temporary_cursor);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1977
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1978 1979 1980 1981
    *c = result;
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
1982
static int toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
1983
    HANDLE_PANICKED_DB(db);
1984
    int r;
Yoni Fogel's avatar
 
Yoni Fogel committed
1985

Yoni Fogel's avatar
 
Yoni Fogel committed
1986 1987
    //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
1988 1989
        DB* pdb;
        DBT data;
Yoni Fogel's avatar
 
Yoni Fogel committed
1990 1991
        DBT pkey;
        DBT *pdb_key;
Yoni Fogel's avatar
 
Yoni Fogel committed
1992
        struct list *h;
1993
        u_int32_t brtflags;
Yoni Fogel's avatar
 
Yoni Fogel committed
1994 1995

        memset(&data, 0, sizeof(data));
Yoni Fogel's avatar
Yoni Fogel committed
1996
        data.flags = DB_DBT_REALLOC;
1997 1998

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

            /* 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.
2011
            r = toku_db_cursor(db, txn, &dbc, 0, 1);
2012
            if (r!=0) return r;
2013 2014
            r = toku_c_get_noassociate(dbc, key, &data, DB_SET);
            while (r==0) {
Rich Prohaska's avatar
Rich Prohaska committed
2015
                r = toku_c_del(dbc, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2016
                if (r==0) found = TRUE;
2017
                if (r!=0 && r!=DB_KEYEMPTY) break;
Yoni Fogel's avatar
Yoni Fogel committed
2018 2019 2020 2021 2022 2023
                /* key is an input-only parameter.  it can have flags such as
                 * DB_DBT_MALLOC.  If this were the case, we would clobber the
                 * contents of key as well as possibly have a memory leak if we
                 * pass it to toku_c_get_noassociate below.  We use a temporary
                 * junk variable to avoid this. */
                r = toku_c_get_noassociate(dbc, &tmp_key, &data, DB_NEXT_DUP);
2024
                if (r == DB_NOTFOUND) {
Yoni Fogel's avatar
Yoni Fogel committed
2025 2026
                    //If we deleted at least one we're happy.  Quit out.
                    if (found) r = 0;
2027
                    break;
2028 2029
                }
            }
Yoni Fogel's avatar
Yoni Fogel committed
2030 2031
            if (data.data)    toku_free(data.data);
            if (tmp_key.data) toku_free(tmp_key.data);
2032

Rich Prohaska's avatar
Rich Prohaska committed
2033
            r2 = toku_c_close(dbc);
2034 2035 2036 2037
            if (r != 0) return r;
            return r2;
        }

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

        cleanup();

Yoni Fogel's avatar
 
Yoni Fogel committed
2079 2080
    	//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
2081
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
2082
    r = toku_db_del_noassociate(db, txn, key, flags);
Rich Prohaska's avatar
Rich Prohaska committed
2083
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2084
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2085

Rich Prohaska's avatar
Rich Prohaska committed
2086 2087 2088 2089
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

2090
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2091
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2092
    int r;
2093

Rich Prohaska's avatar
Rich Prohaska committed
2094
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
2095 2096
        return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
2097 2098 2099 2100
    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;
2101
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2102 2103 2104 2105
    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;
2106 2107 2108
}

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

Rich Prohaska's avatar
Rich Prohaska committed
2118 2119 2120
    if ((db->i->open_flags & DB_THREAD) && (db_thread_need_flags(pkey) || db_thread_need_flags(data)))
        return EINVAL;

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

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

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

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

Yoni Fogel's avatar
Yoni Fogel committed
2219
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2220
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
2221 2222 2223 2224 2225 2226 2227
    assert(txn && lt);
    toku_lth* lth = txn->i->lth;
    assert(lth);

    toku_lock_tree* find = toku_lth_find(lth, lt);
    if (find) {
        assert(find == lt);
Yoni Fogel's avatar
Yoni Fogel committed
2228 2229
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2230
    }
Yoni Fogel's avatar
Yoni Fogel committed
2231 2232 2233 2234 2235 2236
    r = toku_lth_insert(lth, lt);
    if (r != 0) { goto cleanup; }
    
    toku_lt_add_ref(lt);
    r = 0;
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
2237 2238 2239
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2240 2241 2242
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
2243

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

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

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

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

2266 2267 2268 2269 2270 2271 2272 2273
    /* 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;

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

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

Yoni Fogel's avatar
Yoni Fogel committed
2313

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

Yoni Fogel's avatar
Yoni Fogel committed
2322
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
2323 2324 2325 2326
        unsigned int brtflags;
        BOOL dups;
        toku_brt_get_flags(db->i->brt, &brtflags);
        dups = (brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP);
Yoni Fogel's avatar
Yoni Fogel committed
2327 2328 2329 2330 2331 2332

        r = toku_db_id_create(&db->i->db_id, db->i->full_fname,
                              db->i->database_name);
        if (r!=0) { goto error_cleanup; }
        r = toku_ltm_get_lt(db->dbenv->i->ltm, &db->i->lt, dups, db->i->db_id);
        if (r!=0) { goto error_cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
2333
    }
Yoni Fogel's avatar
Yoni Fogel committed
2334

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

2357 2358
static int toku_db_put_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
2359

2360
    unsigned int brtflags;
2361
    r = toku_brt_get_flags(db->i->brt, &brtflags); assert(r == 0);
2362 2363 2364

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

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

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

2439
static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2440
    HANDLE_PANICKED_DB(db);
2441 2442
    int r;

2443
    //Cannot put directly into a secondary.
2444
    if (db->i->primary != 0) return EINVAL;
2445

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

2460
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
2461
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2462 2463 2464 2465 2466 2467
    int r = ENOSYS;
    int r2 = 0;
    toku_db_id* db_id = NULL;
    BOOL need_close   = TRUE;
    char* full_name   = NULL;
    toku_ltm* ltm     = NULL;
Yoni Fogel's avatar
Yoni Fogel committed
2468 2469

    //TODO: Verify DB* db not yet opened
Yoni Fogel's avatar
Yoni Fogel committed
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
    r = toku_db_open(db, NULL, fname, dbname, DB_BTREE, 0, 0777);
    if (r!=0) { goto cleanup; }
    if (db->i->lt) {
        /* Lock tree exists, therefore:
           * Non-private environment (since we are using transactions)
           * Environment will exist after db->close */
        if (db->i->db_id) {
            /* 'copy' the db_id */
            db_id = db->i->db_id;
            toku_db_id_add_ref(db_id);
        }
        if (db->dbenv->i->ltm) { ltm = db->dbenv->i->ltm; }
    }
    
Yoni Fogel's avatar
Yoni Fogel committed
2485 2486 2487
    if (dbname) {
        //TODO: Verify the target db is not open
        //TODO: Use master database (instead of manual edit) when implemented.
2488
        r = toku_brt_remove_subdb(db->i->brt, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
2489
        if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
2490
    }
Yoni Fogel's avatar
Yoni Fogel committed
2491 2492 2493 2494
    if (!dbname) {
        r = find_db_file(db->dbenv, fname, &full_name);
        if (r!=0) { goto cleanup; }
        assert(full_name);
2495 2496 2497
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
2498
        if (unlink(full_name) != 0) { r = errno; goto cleanup; }
2499 2500 2501 2502
    } else {
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
2503
    }
2504

Yoni Fogel's avatar
Yoni Fogel committed
2505 2506 2507 2508 2509 2510 2511
    if (ltm && db_id) { toku_ltm_invalidate_lt(ltm, db_id); }

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

Yoni Fogel's avatar
Yoni Fogel committed
2515 2516 2517 2518 2519 2520 2521 2522 2523
/* TODO: Either
    -find a way for the DB_ID to survive this rename (i.e. be
     the same before and after
    or
    -Go through all DB_IDs in the ltm, and rename them so we
     have the correct unique ids.
   TODO: Verify the DB file is not in use (either a single db file or
         a file with multi-databases).
*/
2524
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
2525
    HANDLE_PANICKED_DB(db);
2526
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2527 2528
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2529 2530 2531 2532 2533
    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
2534
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2535
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2536

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

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

Rich Prohaska's avatar
Rich Prohaska committed
2549
static int toku_db_set_flags(DB *db, u_int32_t flags) {
2550
    HANDLE_PANICKED_DB(db);
2551

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

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

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

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

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

Rich Prohaska's avatar
Rich Prohaska committed
2602 2603 2604 2605 2606 2607
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
2608 2609 2610
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
2611
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
                                            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;
}

2627
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
2628 2629 2630 2631 2632 2633
    if (!changed) return r;
    if (r==0) return toku_txn_commit(txn, 0);
    toku_txn_abort(txn);
    return r; 
}

2634
static inline int autotxn_db_associate(DB *primary, DB_TXN *txn, DB *secondary,
Yoni Fogel's avatar
Yoni Fogel committed
2635 2636 2637 2638 2639 2640 2641 2642
                                       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
2643 2644
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
2645
    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
2646 2647 2648
}

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

2652
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
2653
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2654
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
2655 2656
              "Cursors in a transaction environment must have transactions.\n");
    }
2657
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2658 2659
}

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

2664
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
2665 2666 2667 2668 2669 2670 2671 2672
                                 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
2673
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2674
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
2675 2676
}

2677
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2678 2679 2680 2681 2682 2683
                                 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
2684 2685 2686
}

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
2687
    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
2688 2689
}

2690
static inline int autotxn_db_pget(DB* db, DB_TXN* txn, DBT* key, DBT* pkey,
Yoni Fogel's avatar
Yoni Fogel committed
2691 2692 2693 2694 2695 2696
                                  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
2697 2698 2699
}

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
2700
    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
2701 2702
}

2703
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
2704 2705 2706 2707 2708
    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
2709 2710 2711
}

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
2712
    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
2713 2714
}

2715
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2716 2717 2718 2719 2720 2721 2722 2723
                                 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
2724
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
2725
    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
2726 2727 2728
}

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

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
2733
    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
2734 2735 2736
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2737
    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
2738 2739 2740
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2741
    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
2742 2743 2744 2745 2746 2747 2748
}

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
2749
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2750 2751 2752
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2753
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2754 2755 2756
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2757
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2758 2759 2760
}

static int locked_db_fd(DB *db, int *fdp) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2761
    toku_ydb_lock(); int r = toku_db_fd(db, fdp); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2762 2763 2764
}

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

2767 2768
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2769 2770 2771
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
Rich Prohaska's avatar
Rich Prohaska committed
2772
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2773
            return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
2774
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2775
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
2776
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2777 2778
        if (r != 0)
            return r;
Rich Prohaska's avatar
Rich Prohaska committed
2779
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2780
        if (r != 0) {
Rich Prohaska's avatar
Rich Prohaska committed
2781
            toku_env_close(env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2782 2783
            return r;
        }
Rich Prohaska's avatar
Rich Prohaska committed
2784
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2785
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2786
    
2787
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2788
    if (result == 0) {
Rich Prohaska's avatar
Rich Prohaska committed
2789
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2790
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2791
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2792 2793
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Rich Prohaska's avatar
Rich Prohaska committed
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
    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;
2813
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2814 2815
    if (result->i == 0) {
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
2816
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2817 2818 2819
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
2820
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2821 2822 2823 2824 2825 2826 2827 2828
    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;
2829 2830 2831
    list_init(&result->i->associated);
    result->i->primary = 0;
    result->i->associate_callback = 0;
2832
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2833 2834 2835
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
2836
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2837 2838
        return ENOMEM;
    }
2839
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2840 2841
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2842
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2843

2844
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2845
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2846 2847 2848 2849
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2850 2851 2852 2853 2854 2855 2856 2857
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
2858 2859 2860
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
2861 2862 2863
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
2864

Rich Prohaska's avatar
Rich Prohaska committed
2865
    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
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
    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
2878 2879
    return DB_VERSION_STRING;
}
2880 2881 2882 2883
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
2884