ydb.c 70.4 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 Tokutek Inc.  All rights reserved."
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3

4 5 6 7 8
#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.";
const char *toku_copyright_string = "Copyright (c) 2007 Tokutek Inc.  All rights reserved.";

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

24 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
/* the ydb big lock serializes access to the tokudb
   every call (including methods) into the tokudb library gets the lock 
   no internal function should invoke a method through an object */

static pthread_mutex_t ydb_big_lock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;

static inline void ydb_lock() {
    int r = pthread_mutex_lock(&ydb_big_lock); assert(r == 0);
}

static inline void ydb_unlock() {
    int r = pthread_mutex_unlock(&ydb_big_lock); assert(r == 0);
}

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

static inline void env_add_ref(DB_ENV *env) {
    env->i->ref_count += 1;
}

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;
}

static int env_is_panicked(DB_ENV *dbenv) {
    if (dbenv==0) return 0;
    return dbenv->i->is_panicked || toku_logger_panicked(dbenv->i->logger);
}

#define HANDLE_PANICKED_ENV(env) ({ if (env_is_panicked(env)) return EINVAL; })
#define HANDLE_PANICKED_DB(db) HANDLE_PANICKED_ENV(db->dbenv)


/* 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);
static int toku_db_cursor(DB *db, DB_TXN * txn, DBC **c, u_int32_t flags);

/* 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
105

106
/* misc */
Yoni Fogel's avatar
Yoni Fogel committed
107
static char *construct_full_name(const char *dir, const char *fname);
108
static int do_associated_inserts (DB_TXN *txn, DBT *key, DBT *data, DB *secondary);
Yoni Fogel's avatar
Yoni Fogel committed
109
    
110

111 112 113 114
// If errcall is set, call it with the format string and optionally the stderrstring (if include_stderrstring).  The prefix is passed as a separate argument.
// If errfile is set, print to the errfile: prefix, fmt string, maybe include the stderr string.
// Both errcall and errfile may be called.
// If errfile is not set and errcall is not set, the use stderr as the errfile.
115
void toku_do_error_all_cases(const DB_ENV * env, int error, int include_stderrstring, int use_stderr_if_nothing_else, const char *fmt, va_list ap) {
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    if (env->i->errcall) {
	// errcall gets prefix sent separately
	// the error message is the printf message, maybe followed by ": " and the dbstrerror (if include_stderrstring is set)
	char buf [4000];
	int count=0;
	if (fmt) {
	    count=vsnprintf(buf, sizeof(buf), fmt, ap);
	}
	if (include_stderrstring) {
	    count+=snprintf(&buf[count], sizeof(buf)-count, ": %s", db_strerror(error));
	}
	env->i->errcall(env, env->i->errpfx, buf);
    }
    {
	FILE *efile=env->i->errfile;
	if (efile==0 && env->i->errcall==0 && use_stderr_if_nothing_else) {
	    efile = stderr;
	}
	if (efile) {
	    if (env->i->errpfx) fprintf(efile, "%s: ", env->i->errpfx);
	    vfprintf(efile, fmt, ap);
	    if (include_stderrstring) {
		fprintf(efile, ": %s", db_strerror(error));
	    }
	}
    }
142 143
}

144 145
// Handle all the error cases (but don't do the default thing.)
static int do_error (DB_ENV *dbenv, int error, const char *string, ...) {
146
    if (toku_logger_panicked(dbenv->i->logger)) dbenv->i->is_panicked=1;
147 148
    va_list ap;
    va_start(ap, string);
149
    toku_do_error_all_cases(dbenv, error, 1, 0, string, ap);
150
    va_end(ap);
151
    return error;
Yoni Fogel's avatar
Yoni Fogel committed
152 153
}

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
154 155
#define barf() ({ fprintf(stderr, "YDB: BARF %s:%d in %s\n", __FILE__, __LINE__, __func__); })
#define barff(fmt,...) ({ fprintf(stderr, "YDB: BARF %s:%d in %s, ", __FILE__, __LINE__, __func__); fprintf(stderr, fmt, __VA_ARGS__); })
156
#define note() ({ fprintf(svtderr, "YDB: Note %s:%d in %s\n", __FILE__, __LINE__, __func__); })
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
157 158
#define notef(fmt,...) ({ fprintf(stderr, "YDB: Note %s:%d in %s, ", __FILE__, __LINE__, __func__); fprintf(stderr, fmt, __VA_ARGS__); })

159
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
160 161 162
static void print_flags(u_int32_t flags) {
    u_int32_t gotit = 0;
    int doneone = 0;
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
163
#define doit(flag) if (flag & flags) { if (doneone) fprintf(stderr, " | "); fprintf(stderr, "%s", #flag);  doneone=1; gotit|=flag; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
164 165 166 167 168 169 170 171 172 173 174
    doit(DB_INIT_LOCK);
    doit(DB_INIT_LOG);
    doit(DB_INIT_MPOOL);
    doit(DB_INIT_TXN);
    doit(DB_CREATE);
    doit(DB_THREAD);
    doit(DB_RECOVER);
    doit(DB_PRIVATE);
    if (gotit != flags)
        fprintf(stderr, "  flags 0x%x not accounted for", flags & ~gotit);
    fprintf(stderr, "\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
175
}
176
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
177

178
static int env_parse_config_line(DB_ENV* dbenv, char *command, char *value) {
Yoni Fogel's avatar
Yoni Fogel committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    int r;
    
    if (!strcmp(command, "set_data_dir")) {
        r = dbenv->set_data_dir(dbenv, value);
    }
    else if (!strcmp(command, "set_tmp_dir")) {
        r = dbenv->set_tmp_dir(dbenv, value);
    }
    else if (!strcmp(command, "set_lg_dir")) {
        r = dbenv->set_lg_dir(dbenv, value);
    }
    else r = -1;
        
    return r;
}

195
static int env_read_config(DB_ENV *env) {
196
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    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;
230
    int index;
Yoni Fogel's avatar
Yoni Fogel committed
231 232 233 234 235 236 237
    
    buffersize = 1<<10; //1KB
    linebuffer = toku_malloc(buffersize);
    if (!linebuffer) {
        r = ENOMEM;
        goto cleanup;
    }
238
    for (linenumber = 1; !eof; linenumber++) {
Yoni Fogel's avatar
Yoni Fogel committed
239
        /* Read a single line. */
240
        for (index = 0; TRUE; index++) {
Yoni Fogel's avatar
Yoni Fogel committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
            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;
                }
            }
260
            linebuffer[index] = ch;
Yoni Fogel's avatar
Yoni Fogel committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274
        }
        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.
275
        while (isspace(*value) && value < end) value++;
Yoni Fogel's avatar
Yoni Fogel committed
276 277 278 279 280 281 282 283 284
        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.
285
        r = env_parse_config_line(env, command, value < end ? value : "");
Yoni Fogel's avatar
Yoni Fogel committed
286 287 288 289
        if (r != 0) goto parseerror;
    }
    if (0) {
readerror:
290
        do_error(env, r, "Error reading from DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
291 292 293
    }
    if (0) {
parseerror:
294
        do_error(env, r, "Error parsing DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
295 296 297 298 299 300 301 302
    }
cleanup:
    if (full_name) toku_free(full_name);
    if (linebuffer) toku_free(linebuffer);
    if (fp) r2 = fclose(fp);
    return r ? r : r2;
}

303
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
304
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
305
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
306

307
    if (env_opened(env)) {
308 309
	return do_error(env, EINVAL, "The environment is already open\n");
    }
Yoni Fogel's avatar
Yoni Fogel committed
310

311 312 313
    if ((flags & DB_USE_ENVIRON) && (flags & DB_USE_ENVIRON_ROOT)) {
	return do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible flags\n");
    }
Yoni Fogel's avatar
Yoni Fogel committed
314 315

    if (home) {
316 317 318
        if ((flags & DB_USE_ENVIRON) || (flags & DB_USE_ENVIRON_ROOT)) {
	    return do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible with specifying a home\n");
	}
Yoni Fogel's avatar
Yoni Fogel committed
319 320
    }
    else if ((flags & DB_USE_ENVIRON) ||
321 322 323
             ((flags & DB_USE_ENVIRON_ROOT) && geteuid() == 0)) home = getenv("DB_HOME");

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

325
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
326
	{
327 328
	struct stat buf;
	r = stat(home, &buf);
329 330 331
	if (r!=0) {
	    return do_error(env, errno, "Error from stat(\"%s\",...)\n", home);
	}
332 333
    }

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
334
    if (!(flags & DB_PRIVATE)) {
335
	return do_error(env, EINVAL, "TokuDB requires DB_PRIVATE when opening an env\n");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
336 337 338 339
    }

    if (env->i->dir)
        toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
340
    env->i->dir = toku_strdup(home);
341 342 343
    if (env->i->dir == 0) {
	return do_error(env, ENOMEM, "Out of memory\n");
    }
Yoni Fogel's avatar
Yoni Fogel committed
344 345 346 347 348 349
    if (0) {
        died1:
        toku_free(env->i->dir);
        env->i->dir = NULL;
        return r;
    }
350
    if ((r = env_read_config(env)) != 0) {
351 352
	goto died1;
    }
Yoni Fogel's avatar
Yoni Fogel committed
353
    
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
354 355
    env->i->open_flags = flags;
    env->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
356 357

    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
358 359
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
360 361 362 363 364
	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) {
	    do_error(env, r, "Could not open logger\n");
365
	died2:
366
	    toku_logger_close(&env->i->logger);
367 368
	    goto died1;
	}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
369 370
    }

371
    r = toku_brt_create_cachetable(&env->i->cachetable, env->i->cachetable_size, ZERO_LSN, env->i->logger);
372
    if (r!=0) goto died2;
373 374 375

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

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
376 377
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
378

379
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
380 381
    // Even if the env is panicedk, try to close as much as we can.
    int is_panicked = env_is_panicked(env);
382
    int r0=0,r1=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
383
    if (env->i->cachetable)
384
        r0=toku_cachetable_close(&env->i->cachetable);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
385
    if (env->i->logger)
386
        r1=toku_logger_close(&env->i->logger);
Yoni Fogel's avatar
Yoni Fogel committed
387 388 389 390 391 392 393 394
    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);
    }
395 396
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
397 398
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
399 400 401
    toku_free(env->i->dir);
    toku_free(env->i);
    toku_free(env);
402
    ydb_unref();
403 404 405
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
406
    if (is_panicked) return EINVAL;
407
    return 0;
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_archive(DB_ENV * env, char **list[], u_int32_t flags) {
411
    env=env; flags=flags; // Suppress compiler warnings.
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
412 413 414
    *list = NULL;
    return 0;
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
415

416
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
417
    HANDLE_PANICKED_ENV(env);
418
    env=env; lsn=lsn;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
419
    barf();
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
420
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
421
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
422

423
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
424
    HANDLE_PANICKED_ENV(env);
425 426
    if (ncache != 1)
        return EINVAL;
427 428 429 430 431
    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
432 433 434
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
435 436
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

437
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
438
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
439 440 441 442 443 444
    *gbytes = env->i->cachetable_size >> 30;
    *bytes = env->i->cachetable_size & ((1<<30)-1);
    *ncache = 1;
    return 0;
}

445 446 447 448
static int locked_env_get_cachesize(DB_ENV *env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
    ydb_lock(); int r = toku_env_get_cachesize(env, gbytes, bytes, ncache); ydb_unlock(); return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
449 450
#endif

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

490
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
491
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
492
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
493

494
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
495 496 497
    env->i->errfile = errfile;
}

498
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
499
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
500
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
501

502
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
503
    HANDLE_PANICKED_ENV(env);
504 505 506
    if (flags != 0 && onoff) {
	return do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags\n");
    }
Rich Prohaska's avatar
Rich Prohaska committed
507
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
508
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
509

510
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
511
    HANDLE_PANICKED_ENV(env);
512 513
    bsize=bsize;
    return do_error(env, EINVAL, "TokuDB does not (yet) support ENV->set_lg_bsize\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
514
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
515

516
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
517
    HANDLE_PANICKED_ENV(env);
518
    if (env_opened(env)) {
519 520
	return do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
    }
521 522

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

533
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
534
    HANDLE_PANICKED_ENV(env);
535 536
    lg_max=lg_max;
    return do_error(env, EINVAL, "TokuDB does not (yet) support set_lg_max\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
537
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
538

539
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
540
    HANDLE_PANICKED_ENV(env);
541 542
    detect=detect;
    return do_error(env, EINVAL, "TokuDB does not (yet) support set_lk_detect\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
543
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
544

545
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
546
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
547 548
    HANDLE_PANICKED_ENV(env);
    lk_max=lk_max;
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
549
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
550
}
551 552 553 554

static int locked_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
    ydb_lock(); int r = toku_env_set_lk_max(env, lk_max); ydb_unlock(); return r;
}
555
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
556

557
//void __toku_env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
558 559
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
560

561
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
562
    HANDLE_PANICKED_ENV(env);
563
    if (env_opened(env)) {
564 565 566 567 568
	return do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
    }
    if (!tmp_dir) {
	return do_error(env, EINVAL, "Tmp dir bust be non-null\n");
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
569 570
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
571
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
572
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
573
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
574

575
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
576 577
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
578
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
579
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
580

581
static int toku_env_txn_checkpoint(DB_ENV * env, u_int32_t kbyte, u_int32_t min, u_int32_t flags) {
582
    env=env; kbyte=kbyte; min=min; flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
583
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
584 585
}

586
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
587 588
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
589
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
590 591
}

592
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
593
void toku_default_errcall(const char *errpfx, char *msg) {
594
#else
595
void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
596 597
    env = env;
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
598 599 600
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}

601
#if _THREAD_SAFE
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
602

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
static void locked_env_err(const DB_ENV * env, int error, const char *fmt, ...) {
    ydb_lock();
    va_list ap;
    va_start(ap, fmt);
    toku_do_error_all_cases(env, error, 1, 1, fmt, ap);
    va_end(ap);
    ydb_unlock();
}

static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
    ydb_lock(); int r = toku_env_open(env, home, flags, mode); ydb_unlock(); return r;
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
    ydb_lock(); int r = toku_env_close(env, flags); ydb_unlock(); return r;
}

static int locked_env_log_archive(DB_ENV * env, char **list[], u_int32_t flags) {
    ydb_lock(); int r = toku_env_log_archive(env, list, flags); ydb_unlock(); return r;
}

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
    ydb_lock(); int r = toku_env_log_flush(env, lsn); ydb_unlock(); return r;
}

static int locked_env_set_cachesize(DB_ENV *env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
    ydb_lock(); int r = toku_env_set_cachesize(env, gbytes, bytes, ncache); ydb_unlock(); return r;
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
    ydb_lock(); int r = toku_env_set_data_dir(env, dir); ydb_unlock(); return r;
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
    ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); ydb_unlock(); return r;
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
    ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); ydb_unlock(); return r;
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
    ydb_lock(); int r = toku_env_set_lg_dir(env, dir); ydb_unlock(); return r;
}

static int locked_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
    ydb_lock(); int r = toku_env_set_lg_max(env, lg_max); ydb_unlock(); return r;
}

static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
    ydb_lock(); int r = toku_env_set_lk_detect(env, detect); ydb_unlock(); return r;
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
    ydb_lock(); int r = toku_env_set_tmp_dir(env, tmp_dir); ydb_unlock(); return r;
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
    ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); ydb_unlock(); return r;
}

static int locked_env_txn_checkpoint(DB_ENV * env, u_int32_t kbyte, u_int32_t min, u_int32_t flags) {
    ydb_lock(); int r = toku_env_txn_checkpoint(env, kbyte, min, flags); ydb_unlock(); return r;
}

static int locked_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
    ydb_lock(); int r = toku_env_txn_stat(env, statp, flags); ydb_unlock(); return r;
}

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

#endif

static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
677
    if (flags!=0) return EINVAL;
678
    DB_ENV *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
679 680 681
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    result->err = locked_env_err;
    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;
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
699
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
700
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
701
#endif
702
    result->set_lk_detect = locked_env_set_lk_detect;
703
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
704
    result->set_lk_max = locked_env_set_lk_max;
705
#endif
706 707 708
    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
709

710
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
711 712 713 714 715
    if (result->i == 0) {
        toku_free(result);
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
716
    result->i->is_panicked=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
717
    result->i->ref_count = 1;
718 719
    result->i->errcall = 0;
    result->i->errpfx = 0;
720
    result->i->errfile = 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
721

722 723 724 725 726 727 728 729 730 731
    {
	int r = toku_logger_create(&result->i->logger);
	if (r!=0) {
	    toku_free(result->i);
	    toku_free(result);
	    return r;
	}
	assert(result->i->logger);
    }

732
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
733 734 735 736
    *envp = result;
    return 0;
}

737 738 739 740 741
int db_env_create(DB_ENV ** envp, u_int32_t flags) {
    ydb_lock(); int r = toku_env_create(envp, flags); ydb_unlock(); return r;
}

static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
742
    HANDLE_PANICKED_ENV(txn->mgrp);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
743
    //notef("flags=%d\n", flags);
744 745 746 747 748 749 750 751 752 753 754 755
    int r;
    int nosync = (flags & DB_TXN_NOSYNC)!=0;
    flags &= ~DB_TXN_NOSYNC;
    if (!txn) return EINVAL;
    if (flags!=0) goto return_invalid;
    r = toku_logger_commit(txn->i->tokutxn, nosync);
    if (0) {
    return_invalid:
	r = EINVAL;
	toku_free(txn->i->tokutxn);
    }
    // Cleanup */
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
756 757 758
    if (txn->i)
        toku_free(txn->i);
    toku_free(txn);
759
    return r; // The txn is no good after the commit.
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
760 761
}

762
static u_int32_t toku_txn_id(DB_TXN * txn) {
763
    HANDLE_PANICKED_ENV(txn->mgrp);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
764 765
    barf();
    abort();
766
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
767 768 769 770
}

static TXNID next_txn = 0;

771
static int toku_txn_abort(DB_TXN * txn) {
772
    HANDLE_PANICKED_ENV(txn->mgrp);
773 774 775 776
    int r = toku_logger_abort(txn->i->tokutxn);
    toku_free(txn->i);
    toku_free(txn);
    return r;
777 778
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
#if _THREAD_SAFE

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) {
    ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); ydb_unlock(); return r;
}

static u_int32_t locked_txn_id(DB_TXN *txn) {
    ydb_lock(); u_int32_t r = toku_txn_id(txn); ydb_unlock(); return r;
}

static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
    ydb_lock(); int r = toku_txn_commit(txn, flags); ydb_unlock(); return r;
}

static int locked_txn_abort(DB_TXN *txn) {
    ydb_lock(); int r = toku_txn_abort(txn); ydb_unlock(); return r;
}

#endif

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
802
    HANDLE_PANICKED_ENV(env);
803
    if (!toku_logger_is_open(env->i->logger)) return do_error(env, EINVAL, "Environment does not have logging enabled\n");
804
    flags=flags;
805
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
806 807 808 809
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
    //notef("parent=%p flags=0x%x\n", stxn, flags);
810
    result->mgrp = env;
811 812 813
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
814
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
815 816
    assert(result->i);
    result->i->parent = stxn;
817
    int r = toku_logger_txn_begin(stxn ? stxn->i->tokutxn : 0, &result->i->tokutxn, next_txn++, env->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
818 819 820 821 822 823
    if (r != 0)
        return r;
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
824
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
825 826
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
827
    return toku_logger_log_commit(txn->i->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
828
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
829
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
830

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
831
int log_compare(const DB_LSN * a, const DB_LSN * b) {
832
    ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
833 834
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
    abort();
835
    ydb_unlock();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
836 837
}

838 839
static int maybe_do_associate_create (DB_TXN*txn, DB*primary, DB*secondary) {
    DBC *dbc;
840
    int r = toku_db_cursor(secondary, txn, &dbc, 0);
841 842
    if (r!=0) return r;
    DBT key,data;
843
    r = toku_c_get(dbc, &key, &data, DB_FIRST);
844
    {
845
	int r2=toku_c_close(dbc);
846 847 848 849 850
	if (r!=DB_NOTFOUND) {
	    return r2;
	}
    }
    /* Now we know the secondary is empty. */
851
    r = toku_db_cursor(primary, txn, &dbc, 0);
852
    if (r!=0) return r;
853
    for (r = toku_c_get(dbc, &key, &data, DB_FIRST); r==0; r = toku_c_get(dbc, &key, &data, DB_NEXT)) {
854 855
	r = do_associated_inserts(txn, &key, &data, secondary);
	if (r!=0) {
856
	    toku_c_close(dbc);
857 858 859 860 861 862
	    return r;
	}
    }
    return 0;
}

863 864 865
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) {
866 867
    HANDLE_PANICKED_DB(primary);
    HANDLE_PANICKED_DB(secondary);
868 869
    unsigned int brtflags;
    
870 871
    if (secondary->i->primary) return EINVAL; // The secondary already has a primary
    if (primary->i->primary)   return EINVAL; // The primary already has a primary
872 873 874 875 876

    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.

877 878 879 880 881 882 883 884 885 886
    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
887 888
    list_push(&primary->i->associated, &secondary->i->associated);
    secondary->i->primary = primary;
889
    if (flags==DB_CREATE) {
890
	// To do this:  If the secondary is empty, then open a cursor on the primary.  Step through it all, doing the callbacks.
891
	// Then insert each callback result into the secondary.
892
	return maybe_do_associate_create(txn, primary, secondary);
893 894
    }
    return 0;
895 896
}

897
static int toku_db_close(DB * db, u_int32_t flags) {
898 899 900 901 902 903 904 905 906 907 908 909 910 911
    if (db->i->primary==0) {
	// It is a primary.  Unlink all the secondaries. */
	while (!list_empty(&db->i->associated)) {
	    assert(list_struct(list_head(&db->i->associated),
			       struct __toku_db_internal,
			       associated)->primary==db);
	    list_remove(list_head(&db->i->associated));
	}
    } else {
	// It is a secondary.  Remove it from the list, (which it must be in .*/
	if (!list_empty(&db->i->associated)) {
	    list_remove(&db->i->associated);
	}
    }
912
    flags=flags;
913
    int r = toku_close_brt(db->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
914 915 916
    if (r != 0)
        return r;
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
917
    int is_panicked = env_is_panicked(db->dbenv); // Even if panicked, let's close as much as we can.
918
    env_unref(db->dbenv);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
919 920 921 922
    toku_free(db->i->database_name);
    toku_free(db->i->full_fname);
    toku_free(db->i);
    toku_free(db);
923
    ydb_unref();
924
    if (r==0 && is_panicked) return EINVAL;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
925 926 927
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
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));
    secondary->i->associate_callback(secondary, pkey, data, &idx);
    if (r==DB_DONOTINDEX) return DB_SECONDARY_BAD;
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
        return EINVAL; // We aren't ready for this
    }
#endif
	if (skey->size != idx.size || memcmp(skey->data, idx.data, idx.size) != 0) r = DB_SECONDARY_BAD;
    if (idx.flags & DB_DBT_APPMALLOC) {
    	free(idx.data);
    }
    return r;
}

948 949 950 951 952 953 954 955 956 957 958
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

static int toku_c_get_next_dup(DBC *c, DBT *key, DBT *data) {
    int r;
    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 nkey; memset(&nkey, 0, sizeof nkey); nkey.flags = DB_DBT_REALLOC;
    DBT nval; memset(&nval, 0, sizeof nval); nval.flags = DB_DBT_REALLOC;
959
    r = toku_c_get_noassociate(c, &currentkey, &currentval, DB_CURRENT+256); 
960
    if (r != 0) goto finish;
961
    r = toku_c_get_noassociate(c, &nkey, &nval, DB_NEXT);
962
    if (r != 0) {
963
        int rr = toku_c_get_noassociate(c, &nkey, &nval, DB_LAST); if (0) assert(rr == 0); /* sticky */
964 965 966
        goto finish;
    }
    if (!keyeq(c, &currentkey, &nkey)) {
967
        int rr = toku_c_get_noassociate(c, &nkey, &nval, DB_PREV); if (0) assert(rr == 0); /* sticky */
968 969 970
        r = DB_NOTFOUND;
        goto finish;
    }
971
    r = toku_c_get_noassociate(c, key, data, DB_CURRENT);
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
finish:
    if (nkey.data) toku_free(nkey.data);
    if (nval.data) toku_free(nval.data);
    if (currentkey.data) toku_free(currentkey.data);
    if (currentval.data) toku_free(currentval.data);
    return r;
}

#ifdef DB_PREV_DUP

static int toku_c_get_prev_dup(DBC *c, DBT *key, DBT *data) {
    int r;
    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 nkey; memset(&nkey, 0, sizeof nkey); nkey.flags = DB_DBT_REALLOC;
    DBT nval; memset(&nval, 0, sizeof nval); nval.flags = DB_DBT_REALLOC;
988
    r = toku_c_get_noassociate(c, &currentkey, &currentval, DB_CURRENT+256); 
989
    if (r != 0) goto finish;
990
    r = toku_c_get_noassociate(c, &nkey, &nval, DB_PREV);
991
    if (r != 0) {
992
        int rr = toku_c_get_noassociate(c, &nkey, &nval, DB_FIRST); if (0) assert(rr == 0); /* sticky */
993 994 995
        goto finish;
    }
    if (!keyeq(c, &currentkey, &nkey)) {
996
        int rr = toku_c_get_noassociate(c, &nkey, &nval, DB_NEXT); if (0) assert(rr == 0); /* sticky */
997 998 999
        r = DB_NOTFOUND;
        goto finish;
    }
1000
    r = toku_c_get_noassociate(c, key, data, DB_CURRENT);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
finish:
    if (nkey.data) toku_free(nkey.data);
    if (nval.data) toku_free(nval.data);
    if (currentkey.data) toku_free(currentkey.data);
    if (currentval.data) toku_free(currentval.data);
    return r;
}

#endif

static int toku_c_get_next_nodup(DBC *c, DBT *key, DBT *data) {
    int r;
    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 nkey; memset(&nkey, 0, sizeof nkey); nkey.flags = DB_DBT_REALLOC;
    DBT nval; memset(&nval, 0, sizeof nval); nval.flags = DB_DBT_REALLOC;
1017
    r = toku_c_get_noassociate(c, &currentkey, &currentval, DB_CURRENT+256); 
1018
    if (r != 0)
1019
        r = toku_c_get_noassociate(c, key, data, DB_FIRST);
1020 1021
    else {
        while (r == 0) {
1022
            r = toku_c_get_noassociate(c, &nkey, &nval, DB_NEXT);
1023 1024 1025
            if (r != 0) break;
            if (!keyeq(c, &currentkey, &nkey)) break;
        }
1026
        if (r == 0) r = toku_c_get_noassociate(c, key, data, DB_CURRENT);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    }
    if (nkey.data) toku_free(nkey.data);
    if (nval.data) toku_free(nval.data);
    if (currentkey.data) toku_free(currentkey.data);
    if (currentval.data) toku_free(currentval.data);
    return r;
}

static int toku_c_get_prev_nodup(DBC *c, DBT *key, DBT *data) {
    int r;
    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 nkey; memset(&nkey, 0, sizeof nkey); nkey.flags = DB_DBT_REALLOC;
    DBT nval; memset(&nval, 0, sizeof nval); nval.flags = DB_DBT_REALLOC;
1041
    r = toku_c_get_noassociate(c, &currentkey, &currentval, DB_CURRENT+256); 
1042
    if (r != 0)
1043
        r = toku_c_get_noassociate(c, key, data, DB_LAST);
1044 1045
    else {
        while (r == 0) {
1046
            r = toku_c_get_noassociate(c, &nkey, &nval, DB_PREV);
1047 1048 1049
            if (r != 0) break;
            if (!keyeq(c, &currentkey, &nkey)) break;
        }
1050
        if (r == 0) r = toku_c_get_noassociate(c, key, data, DB_CURRENT);
1051 1052 1053 1054 1055 1056 1057 1058
    }
    if (nkey.data) toku_free(nkey.data);
    if (nval.data) toku_free(nval.data);
    if (currentkey.data) toku_free(currentkey.data);
    if (currentval.data) toku_free(currentval.data);
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1059
static int toku_c_get_noassociate(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1060
    HANDLE_PANICKED_DB(c->dbp);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    int r;
    u_int32_t op = flag & DB_OPFLAGS_MASK;
    if (op == DB_NEXT_DUP)
        r = toku_c_get_next_dup(c, key, data);
    else if (op == DB_NEXT_NODUP)
        r = toku_c_get_next_nodup(c, key, data);
    else if (op == DB_PREV_NODUP) 
        r = toku_c_get_prev_nodup(c, key, data);
#ifdef DB_PREV_DUP
    else if (op == DB_PREV_DUP)
        r = toku_c_get_prev_dup(c, key, data);
#endif
    else
        r = toku_brt_cursor_get(c->i->c, key, data, flag, c->i->txn ? c->i->txn->i->tokutxn : 0);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1075 1076 1077
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1078
static int toku_c_del_noassociate(DBC * c, u_int32_t flags) {
1079
    HANDLE_PANICKED_DB(c->dbp);
1080
    int r = toku_brt_cursor_delete(c->i->c, flags);
Yoni Fogel's avatar
Yoni Fogel committed
1081 1082 1083
    return r;
}

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
//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;
}

1099 1100
static int toku_c_pget_save_original_data(DBT* dst, DBT* src) {
    int r;
1101
    
1102 1103 1104
    *dst = *src;
#ifdef DB_DBT_PARTIAL
#error toku_c_pget does not properly handle DB_DBT_PARTIAL
1105
#endif
1106 1107 1108 1109 1110 1111
    //We may use this multiple times, we'll free only once at the end.
    dst->flags = DB_DBT_REALLOC;
    //Not using DB_DBT_USERMEM.
    dst->ulen = 0;
    if (src->size) {
        if (!src->data) return EINVAL;
1112
        dst->data = toku_malloc(src->size);
1113 1114 1115
        if (!dst->data) {
            r = ENOMEM;
            return r;
1116
        }
1117
        memcpy(dst->data, src->data, src->size);
1118
    }
1119
    else dst->data = NULL;
1120 1121
    return 0;
}
1122

Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1123 1124
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
    int r;
1125 1126
    int r2;
    int r3;
1127
    DB *db = c->dbp;
1128
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1129
    DB *pdb = db->i->primary;
1130
    
Yoni Fogel's avatar
Yoni Fogel committed
1131 1132 1133 1134
    if (!pdb) return EINVAL;  //c_pget does not work on a primary.
	// If data and primary_key are both zeroed, the temporary storage used to fill in data is different in the two cases because they come from different trees.
	assert(db->i->brt!=pdb->i->brt); // Make sure they realy are different trees.
    assert(db!=pdb);
Yoni Fogel's avatar
Yoni Fogel committed
1135

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    DBT copied_key;
    DBT copied_pkey;
    DBT copied_data;
    //Store original pointers.
    DBT* o_key = key;
    DBT* o_pkey = pkey;
    DBT* o_data = data;
    //Use copied versions for everything until/if success.
    key  = &copied_key;
    pkey = &copied_pkey;
    data = &copied_data;

Yoni Fogel's avatar
Yoni Fogel committed
1148
    if (0) {
1149
delete_silently_and_retry:
1150
        //Free any old data.
1151 1152 1153
        free(key->data);
        free(pkey->data);
        free(data->data);
Yoni Fogel's avatar
Yoni Fogel committed
1154 1155 1156
        //Silently delete and re-run.
        r = toku_c_del_noassociate(c, 0);
        if (r != 0) return r;
1157
    }
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    if (0) {
        died0:
        return r;
    }
    //Need to save all the original data.
    r = toku_c_pget_save_original_data(&copied_key, o_key);   if (r!=0) goto died0;
    if (0) {
        died1:
        free(key->data);
        goto died0;
    }
    r = toku_c_pget_save_original_data(&copied_pkey, o_pkey); if (r!=0) goto died1;
    if (0) {
        died2:
        free(pkey->data);
        goto died1;
    }
    r = toku_c_pget_save_original_data(&copied_data, o_data); if (r!=0) goto died2;
    if (0) {
        died3:
        free(data->data);
        goto died2;
    }

Yoni Fogel's avatar
Yoni Fogel committed
1182
    r = toku_c_get_noassociate(c, key, pkey, flag);
1183
    if (r != 0) goto died3;
1184
    r = toku_db_get(pdb, c->i->txn, pkey, data, 0);
1185
    if (r == DB_NOTFOUND)   goto delete_silently_and_retry;
1186
    if (r != 0) goto died3;
Yoni Fogel's avatar
Yoni Fogel committed
1187
    r = verify_secondary_key(db, pkey, data, key);
1188
    if (r != 0)             goto delete_silently_and_retry;
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203

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

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

    //Cleanup.
    free(key->data);
    free(pkey->data);
    free(data->data);
    if (r!=0) return r;
    if (r2!=0) return r2;
    return r3;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1204 1205
}

Yoni Fogel's avatar
Yoni Fogel committed
1206
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1207
    DB *db = c->dbp;
1208
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1209 1210 1211 1212 1213 1214
    int r;

    if (db->i->primary==0) r = toku_c_get_noassociate(c, key, data, flag);
    else {
        // It's a c_get on a secondary.
        DBT primary_key;
1215
        u_int32_t get_flag = get_main_cursor_flag(flag);
Yoni Fogel's avatar
Yoni Fogel committed
1216 1217 1218 1219
        
        /* 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
1220 1221 1222 1223 1224
        if ((get_flag == DB_GET_BOTH)
#ifdef DB_GET_BOTH_RANGE
            || (get_flag == DB_GET_BOTH_RANGE)
#endif
        ) return EINVAL;
Yoni Fogel's avatar
Yoni Fogel committed
1225 1226 1227 1228 1229 1230
        memset(&primary_key, 0, sizeof(primary_key));
        r = toku_c_pget(c, key, &primary_key, data, flag);
    }
    return r;
}

1231
static int toku_c_close(DBC * c) {
1232
    int r = toku_brt_cursor_close(c->i->c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1233 1234
    toku_free(c->i);
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1235 1236 1237
    return r;
}

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
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;
    }

    r = toku_c_get(cursor, &currentkey, &currentval, DB_CURRENT+256);
    if (r != 0) goto finish;
    
    r = toku_db_cursor(cursor->dbp, 0, &count_cursor, 0);
    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;
}

1280 1281 1282
static int toku_db_get_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
    unsigned int brtflags;
1283
    if (flags!=0 && flags!=DB_GET_BOTH) return EINVAL;
1284 1285
    
    toku_brt_get_flags(db->i->brt, &brtflags);
Yoni Fogel's avatar
Yoni Fogel committed
1286
    if ((brtflags & TOKU_DB_DUPSORT) || flags == DB_GET_BOTH) {
1287

1288 1289
        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
1290
        
1291
        DBC *dbc;
1292
        r = toku_db_cursor(db, txn, &dbc, 0);
1293
        if (r!=0) return r;
1294
        r = toku_c_get_noassociate(dbc, key, data, flags == DB_GET_BOTH ? DB_GET_BOTH : DB_SET);
1295
        int r2 = toku_c_close(dbc);
1296 1297
        if (r!=0) return r;
        return r2;
1298
    } else {
1299
        if (flags != 0) return EINVAL;
1300
        return toku_brt_lookup(db->i->brt, key, data);
1301 1302 1303 1304 1305
    }
}

static int toku_db_del_noassociate(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
    int r;
1306
    if (flags!=0 && flags!=DB_DELETE_ANY) return EINVAL;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    //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;
        free(search_val.data);
    } 
    //Do the actual deleting.
    r = toku_brt_delete(db->i->brt, key);
    return r;
}

Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1321
static int do_associated_deletes(DB_TXN *txn, DBT *key, DBT *data, DB *secondary) {
1322
    u_int32_t brtflags;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1323 1324 1325
    DBT idx;
    memset(&idx, 0, sizeof(idx));
    int r = secondary->i->associate_callback(secondary, key, data, &idx);
1326
    int r2 = 0;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1327 1328 1329 1330 1331 1332
    if (r==DB_DONOTINDEX) return 0;
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
        return EINVAL; // We aren't ready for this
    }
#endif
1333 1334
    toku_brt_get_flags(secondary->i->brt, &brtflags);
    if (brtflags & TOKU_DB_DUPSORT) {
1335
        //If the secondary has duplicates we need to use cursor deletes.
1336 1337 1338 1339 1340 1341 1342
        DBC *dbc;
        r = toku_db_cursor(secondary, txn, &dbc, 0);
        if (r!=0) goto cleanup;
        r = toku_c_get_noassociate(dbc, &idx, key, DB_GET_BOTH);
        if (r!=0) goto cleanup;
        r = toku_c_del_noassociate(dbc, 0);
    cleanup:
1343
        r2 = toku_c_close(dbc);
1344 1345
    } else 
        r = toku_db_del_noassociate(secondary, txn, &idx, DB_DELETE_ANY);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1346 1347 1348
    if (idx.flags & DB_DBT_APPMALLOC) {
    	free(idx.data);
    }
1349 1350
    if (r!=0) return r;
    return r2;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1351 1352
}

1353
static int toku_c_del(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1354
    int r;
1355
    DB* db = c->dbp;
1356
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1357
    
1358
    //It is a primary with secondaries, or is a secondary.
1359
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1360 1361 1362 1363 1364 1365 1366 1367 1368
        DB* pdb;
        DBT pkey;
        DBT data;
        struct list *h;

        memset(&pkey, 0, sizeof(pkey));
        memset(&data, 0, sizeof(data));
        if (db->i->primary == 0) {
            pdb = db;
1369 1370
            r = toku_c_get(c, &pkey, &data, DB_CURRENT);
        } else {
1371
            DBT skey;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1372
            pdb = db->i->primary;
1373 1374
            memset(&skey, 0, sizeof(skey));
            r = toku_c_pget(c, &skey, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        }
        if (r != 0) return r;
        
    	for (h = list_head(&pdb->i->associated); h != &pdb->i->associated; h = h->next) {
    	    struct __toku_db_internal *dbi = list_struct(h, struct __toku_db_internal, associated);
    	    if (dbi->db == db) continue;  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(c->i->txn, &pkey, &data, dbi->db);
    	    if (r!=0) return r;
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
1386 1387
    	    //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
1388 1389 1390
    	    if (r!=0) return r;
    	}
    }
1391 1392
    r = toku_c_del_noassociate(c, flags);
    return r;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1393 1394
}

1395
static int toku_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
1396
    DB* db = dbc->dbp;
1397
    HANDLE_PANICKED_DB(db);
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    unsigned int brtflags;
    int r;
    DBT* put_key  = key;
    DBT* put_data = data;
    DBT* get_key  = key;
    DBT* get_data = data;
    
    //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) {
                free(key_local.data);
                free(data_local.data);
            }
            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.
        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
1451
    //Flags must NOT be 0.
1452 1453
    else return EINVAL;
finish:
1454 1455
    //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.
1456 1457 1458 1459 1460
    if (r!=0) goto cleanup;
    r = toku_c_get(dbc, get_key, get_data, DB_GET_BOTH);
    goto cleanup;
}

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
#if _THREAD_SAFE

static int locked_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
    ydb_lock(); int r = toku_c_pget(c, key, pkey, data, flag); ydb_unlock(); return r;
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
    ydb_lock(); int r = toku_c_get(c, key, data, flag); ydb_unlock(); return r;
}

static int locked_c_close(DBC * c) {
    ydb_lock(); int r = toku_c_close(c); ydb_unlock(); return r;
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
    ydb_lock(); int r = toku_c_count(cursor, count, flags); ydb_unlock(); return r;
}

static int locked_c_del(DBC * c, u_int32_t flags) {
    ydb_lock(); int r = toku_c_del(c, flags); ydb_unlock(); return r;
}

static int locked_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
    ydb_lock(); int r = toku_c_put(dbc, key, data, flags); ydb_unlock(); return r;
}

#endif

1489
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags) {
1490
    HANDLE_PANICKED_DB(db);
1491 1492
    if (flags != 0)
        return EINVAL;
1493
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1494 1495 1496
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
1497 1498 1499 1500 1501 1502
    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;
1503
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1504
    assert(result->i);
1505
    result->dbp = db;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1506
    result->i->txn = txn;
1507
    int r = toku_brt_cursor(db->i->brt, &result->i->c);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1508
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1509 1510 1511 1512
    *c = result;
    return 0;
}

1513
static int toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
1514
    HANDLE_PANICKED_DB(db);
1515
    int r;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1516

1517 1518
    //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
1519 1520
        DB* pdb;
        DBT data;
1521 1522
        DBT pkey;
        DBT *pdb_key;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1523
        struct list *h;
1524
        u_int32_t brtflags;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1525 1526

        memset(&data, 0, sizeof(data));
1527 1528

        toku_brt_get_flags(db->i->brt, &brtflags);
Rich Prohaska's avatar
Rich Prohaska committed
1529
        if (brtflags & TOKU_DB_DUPSORT) {
1530 1531
            int r2;
    	    DBC *dbc;
Yoni Fogel's avatar
Yoni Fogel committed
1532
    	    BOOL found = FALSE;
1533 1534 1535 1536 1537

            /* 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.
Rich Prohaska's avatar
Rich Prohaska committed
1538
            r = toku_db_cursor(db, txn, &dbc, 0);
1539
            if (r!=0) return r;
1540 1541
            r = toku_c_get_noassociate(dbc, key, &data, DB_SET);
            while (r==0) {
1542
                r = toku_c_del(dbc, 0);
Yoni Fogel's avatar
Yoni Fogel committed
1543
                if (r==0) found = TRUE;
1544
                if (r!=0 && r!=DB_KEYEMPTY) break;
1545 1546
                r = toku_c_get_noassociate(dbc, key, &data, DB_NEXT_DUP);
                if (r == DB_NOTFOUND) {
Yoni Fogel's avatar
Yoni Fogel committed
1547 1548
                    //If we deleted at least one we're happy.  Quit out.
                    if (found) r = 0;
1549
                    break;
1550 1551
                }
            }
1552

1553
            r2 = toku_c_close(dbc);
1554 1555 1556 1557
            if (r != 0) return r;
            return r2;
        }

1558 1559 1560 1561 1562 1563 1564 1565
        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
1566 1567
        if (db->i->primary == 0) {
            pdb = db;
1568
            r = toku_db_get(db, txn, key, &data, 0);
1569
            pdb_key = key;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1570 1571 1572
        }
        else {
            pdb = db->i->primary;
1573
            r = toku_db_pget(db, txn, key, &pkey, &data, 0);
1574
            pdb_key = &pkey;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1575
        }
1576 1577 1578
        if (r != 0) { 
            cleanup(); return r; 
        }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1579 1580 1581
        
    	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);
1582 1583
    	    if (dbi->db == db) continue;                  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(txn, pdb_key, &data, dbi->db);
1584 1585 1586
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1587 1588 1589
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
1590 1591
    	    //Primaries cannot have duplicates, (noncursor) del is safe.
    	    r = toku_db_del_noassociate(pdb, txn, pdb_key, DB_DELETE_ANY);
1592 1593 1594
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1595
    	}
1596 1597 1598

        cleanup();

1599 1600
    	//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
1601
    }
1602
    r = toku_db_del_noassociate(db, txn, key, flags);
Rich Prohaska's avatar
Rich Prohaska committed
1603
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1604
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1605

Rich Prohaska's avatar
Rich Prohaska committed
1606 1607 1608 1609
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

1610
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
1611
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1612
    int r;
1613

Rich Prohaska's avatar
Rich Prohaska committed
1614
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
1615 1616
        return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
1617
    if (db->i->primary==0) r = toku_db_get_noassociate(db, txn, key, data, flags);
1618 1619
    else {
        // It's a get on a secondary.
Yoni Fogel's avatar
Yoni Fogel committed
1620 1621
        if (flags == DB_GET_BOTH) return EINVAL;
        assert(flags == 0); // We aren't ready to handle flags such as DB_READ_COMMITTED or DB_READ_UNCOMMITTED or DB_RMW
Rich Prohaska's avatar
Rich Prohaska committed
1622 1623 1624
        DBT primary_key; memset(&primary_key, 0, sizeof(primary_key)); primary_key.flags = DB_DBT_MALLOC;
        r = toku_db_pget(db, txn, key, &primary_key, data, 0);
        if (primary_key.data) toku_free(primary_key.data);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1625
    }
Yoni Fogel's avatar
Yoni Fogel committed
1626
    return r;
1627 1628 1629
}

static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
1630
    HANDLE_PANICKED_DB(db);
1631
    int r;
1632 1633
    int r2;
    DBC *dbc;
1634 1635
    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
1636
    assert(db->i->brt != db->i->primary->i->brt); // Make sure they realy are different trees.
1637
    assert(db!=db->i->primary);
1638

Rich Prohaska's avatar
Rich Prohaska committed
1639 1640 1641
    if ((db->i->open_flags & DB_THREAD) && (db_thread_need_flags(pkey) || db_thread_need_flags(data)))
        return EINVAL;

1642
    r = toku_db_cursor(db, txn, &dbc, 0);
1643
    if (r!=0) return r;
1644
    r = toku_c_pget(dbc, key, pkey, data, DB_SET);
Yoni Fogel's avatar
Yoni Fogel committed
1645
    if (r==DB_KEYEMPTY) r = DB_NOTFOUND;
1646
    r2 = toku_c_close(dbc);
1647 1648
    if (r!=0) return r;
    return r2;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1649 1650
}

1651
#if 0
1652
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
1653 1654
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1655 1656
    barf();
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1657
}
1658
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1659

Yoni Fogel's avatar
Yoni Fogel committed
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
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
1680 1681 1682
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
1683
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1684 1685 1686 1687
        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
1688 1689 1690 1691
        // 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
1692 1693
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1694 1695 1696
    }
}

1697
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel 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 1724 1725 1726 1727 1728 1729
    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);
                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;    
}

1730
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
1731
    HANDLE_PANICKED_DB(db);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1732 1733
    // Warning.  Should check arguments.  Should check return codes on malloc and open and so forth.

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1734
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1735
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1736
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
1737 1738 1739 1740
    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;
    int is_db_unknown = flags & DB_UNKNOWN; flags&=~DB_UNKNOWN;
1741
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
1742 1743 1744

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

1746
    if (db_opened(db))
1747
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
1748 1749 1750
    
    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
1751
    // printf("Full name = %s\n", db->i->full_fname);
Yoni Fogel's avatar
Yoni Fogel committed
1752
    db->i->database_name = toku_strdup(dbname ? dbname : "");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1753 1754 1755 1756
    if (db->i->database_name == 0) {
        r = ENOMEM;
        goto error_cleanup;
    }
1757
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1758 1759 1760
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
1761
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1762
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1763 1764 1765
        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. */
1766 1767
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
1768 1769 1770
                    r = EEXIST;
                    goto error_cleanup;
                }
1771
		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
1772 1773
            }
        } else {
1774
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1775 1776 1777 1778
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1779
    }
1780
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1781 1782 1783

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

1785
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname, dbname,
1786 1787 1788
		      is_db_create, is_db_excl, is_db_unknown,
		      db->dbenv->i->cachetable,
		      txn ? txn->i->tokutxn : NULL_TXN);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1789 1790 1791
    if (r != 0)
        goto error_cleanup;

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1792
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
 
error_cleanup:
    if (db->i->database_name) {
        toku_free(db->i->database_name);
        db->i->database_name = NULL;
    }
    if (db->i->full_fname) {
        toku_free(db->i->full_fname);
        db->i->full_fname = NULL;
    }
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1804
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1805

1806 1807
static int toku_db_put_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
1808

1809
    unsigned int brtflags;
1810
    r = toku_brt_get_flags(db->i->brt, &brtflags); assert(r == 0);
1811 1812 1813

    /* limit the size of key and data */
    unsigned int nodesize;
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    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)
            return EINVAL;
    }
1824 1825 1826 1827 1828 1829 1830

    if (flags == DB_YESOVERWRITE) {
        /* tokudb does insert or replace */
        ;
    } else if (flags == DB_NOOVERWRITE) {
        /* check if the key already exists */
        DBT testfordata;
1831
        r = toku_db_get_noassociate(db, txn, key, toku_init_dbt(&testfordata), 0);
1832 1833 1834 1835 1836 1837
        if (r == 0)
            return DB_KEYEXIST;
    } else if (flags != 0) {
        /* no other flags are currently supported */
        return EINVAL;
    } else {
1838
        assert(flags == 0);
1839
        if (brtflags & TOKU_DB_DUPSORT) {
1840
#if TDB_EQ_BDB
1841
            r = toku_db_get_noassociate(db, txn, key, data, DB_GET_BOTH);
1842 1843
            if (r == 0)
                return DB_KEYEXIST;
1844
#else
1845
	    return do_error(db->dbenv, EINVAL, "Tokudb requires that db->put specify DB_YESOVERWRITE or DB_NOOVERWRITE on DB_DUPSORT databases");
1846
#endif
1847 1848
        }
    }
1849 1850 1851 1852 1853 1854
    
    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;
}

1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
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);
    if (r==DB_DONOTINDEX) return 0;
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
	return EINVAL; // We aren't ready for this
    }
#endif
1865
    r = toku_db_put_noassociate(secondary, txn, &idx, key, DB_YESOVERWRITE);
1866
    if (idx.flags & DB_DBT_APPMALLOC) {
1867
        free(idx.data);
1868 1869 1870 1871
    }
    return r;
}

1872
static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
1873
    HANDLE_PANICKED_DB(db);
1874 1875
    int r;

1876
    //Cannot put directly into a secondary.
1877
    if (db->i->primary != 0) return EINVAL;
1878

1879
    r = toku_db_put_noassociate(db, txn, key, data, flags);
1880 1881
    if (r!=0) return r;
    // For each secondary add the relevant records.
1882 1883 1884 1885 1886 1887 1888
    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;
1889 1890
    }
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1891
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1892

1893
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
1894
    HANDLE_PANICKED_DB(db);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1895
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1896
    int r2;
Yoni Fogel's avatar
Yoni Fogel committed
1897
    char *full_name;
Yoni Fogel's avatar
Yoni Fogel committed
1898 1899 1900 1901 1902 1903

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

1904
        if ((r = toku_db_open(db, NULL, fname, dbname, DB_BTREE, 0, 0777)) != 0) goto cleanup;
1905
        r = toku_brt_remove_subdb(db->i->brt, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
1906
cleanup:
1907
        r2 = toku_db_close(db, 0);
Yoni Fogel's avatar
Yoni Fogel committed
1908 1909 1910
        return r ? r : r2;
    }
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
Yoni Fogel's avatar
Yoni Fogel committed
1911 1912 1913
    r = find_db_file(db->dbenv, fname, &full_name);
    if (r!=0) return r;
    assert(full_name);
1914
    r2 = toku_db_close(db, 0);
1915
    if (r == 0 && r2 == 0) {
Yoni Fogel's avatar
Yoni Fogel committed
1916
        if (unlink(full_name) != 0) r = errno;
1917
    }
Yoni Fogel's avatar
Yoni Fogel committed
1918
    toku_free(full_name);
Yoni Fogel's avatar
Yoni Fogel committed
1919
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1920
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1921

1922
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
1923
    HANDLE_PANICKED_DB(db);
1924
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1925 1926
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1927 1928 1929 1930 1931
    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
1932
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1933
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1934

1935
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
1936
    HANDLE_PANICKED_DB(db);
1937
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1938 1939 1940
    return r;
}

1941
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
1942
    HANDLE_PANICKED_DB(db);
1943
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1944 1945 1946
    return r;
}

1947
static int toku_db_set_flags(DB *db, u_int32_t flags) {
1948
    HANDLE_PANICKED_DB(db);
1949

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

Yoni Fogel's avatar
Yoni Fogel committed
1953 1954 1955 1956
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
1957 1958 1959 1960 1961
    /* we support no duplicates and sorted duplicates */
    if (flags) {
        if (flags != (DB_DUP + DB_DUPSORT))
            return EINVAL;
        tflags += TOKU_DB_DUP + TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
1962 1963
    }
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1964 1965 1966
    return r;
}

1967
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
1968
    HANDLE_PANICKED_DB(db);
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
    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;
}

1987
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
1988
    HANDLE_PANICKED_DB(db);
1989
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1990
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1991
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1992

1993
#if 0
1994
static int toku_db_stat(DB * db, void *v, u_int32_t flags) {
1995 1996
    HANDLE_PANICKED_DB(db);
    v=v; flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1997 1998 1999
    barf();
    abort();
}
2000
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2001

Rich Prohaska's avatar
Rich Prohaska committed
2002 2003 2004 2005 2006 2007
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);
}

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
#if _THREAD_SAFE

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) {
    ydb_lock(); int r = toku_db_associate(primary, txn, secondary, callback, flags); ydb_unlock(); return r;
}

static int locked_db_close(DB * db, u_int32_t flags) {
    ydb_lock(); int r = toku_db_close(db, flags); ydb_unlock(); return r;
}

static int locked_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
    ydb_lock(); int r = toku_db_cursor(db, txn, c, flags); ydb_unlock(); return r;
}

static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
    ydb_lock(); int r = toku_db_del(db, txn, key, flags); ydb_unlock(); return r;
}

static int locked_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    ydb_lock(); int r = toku_db_get(db, txn, key, data, flags); ydb_unlock(); return r;
}

static int locked_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
    ydb_lock(); int r = toku_db_pget(db, txn, key, pkey, data, flags); ydb_unlock(); return r;
}

static int locked_db_open(DB *db, DB_TXN *txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
    ydb_lock(); int r = toku_db_open(db, txn, fname, dbname, dbtype, flags, mode); ydb_unlock(); return r;
}

static int locked_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    ydb_lock(); int r = toku_db_put(db, txn, key, data, flags); ydb_unlock(); return r;
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
    ydb_lock(); int r = toku_db_remove(db, fname, dbname, flags); ydb_unlock(); return r;
}

static int locked_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
    ydb_lock(); int r = toku_db_rename(db, namea, nameb, namec, flags); ydb_unlock(); return r;
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
    ydb_lock(); int r = toku_db_set_bt_compare(db, bt_compare); ydb_unlock(); return r;
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
    ydb_lock(); int r = toku_db_set_dup_compare(db, dup_compare); ydb_unlock(); return r;
}

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) {
    ydb_lock(); int r = toku_db_set_flags(db, flags); ydb_unlock(); return r;
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
    ydb_lock(); int r = toku_db_get_flags(db, flags); ydb_unlock(); return r;
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
    ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); ydb_unlock(); return r;
}

static int locked_db_fd(DB *db, int *fdp) {
    ydb_lock(); int r = toku_db_fd(db, fdp); ydb_unlock(); return r;
}

#endif

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

2084 2085
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2086 2087 2088
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
2089
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2090
            return EINVAL;
2091
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2092
    } else {
2093
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2094 2095
        if (r != 0)
            return r;
2096
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2097
        if (r != 0) {
2098
            toku_env_close(env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2099 2100
            return r;
        }
2101
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2102
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2103
    
2104
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2105
    if (result == 0) {
2106
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2107
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2108
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2109 2110
    memset(result, 0, sizeof *result);
    result->dbenv = env;
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
    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;
2130
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2131 2132
    if (result->i == 0) {
        toku_free(result);
2133
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2134 2135 2136
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
2137
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2138 2139 2140 2141 2142 2143 2144 2145
    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;
2146 2147 2148
    list_init(&result->i->associated);
    result->i->primary = 0;
    result->i->associate_callback = 0;
2149
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2150 2151 2152
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
2153
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2154 2155
        return ENOMEM;
    }
2156
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2157 2158
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2159
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2160

2161 2162 2163 2164 2165 2166
int db_create(DB ** db, DB_ENV * env, u_int32_t flags) {
    ydb_lock(); int r = toku_db_create(db, env, flags); ydb_unlock(); return r;
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2167 2168 2169 2170 2171 2172 2173 2174
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
2175 2176 2177 2178
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }

2179
    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
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
    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
2192 2193
    return DB_VERSION_STRING;
}