ldb_mdb.c 19.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
   ldb database library using mdb back end

   Copyright (C) Jakub Hrozek 2014
   Copyright (C) Catalyst.Net Ltd 2017

     ** NOTE! The following LGPL license applies to the ldb
     ** library. This does NOT imply that all of Samba is released
     ** under the LGPL

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/

#include "ldb_mdb.h"
26
#include "../ldb_tdb/ldb_tdb.h"
27 28 29 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
#include "include/dlinklist.h"

#define MDB_URL_PREFIX		"mdb://"
#define MDB_URL_PREFIX_SIZE	(sizeof(MDB_URL_PREFIX)-1)

#define LDB_MDB_MAX_KEY_LENGTH 511

#define GIGABYTE (1024*1024*1024)

int ldb_mdb_err_map(int lmdb_err)
{
	switch (lmdb_err) {
	case MDB_SUCCESS:
		return LDB_SUCCESS;
	case EIO:
		return LDB_ERR_OPERATIONS_ERROR;
	case EBADE:
	case MDB_INCOMPATIBLE:
	case MDB_CORRUPTED:
	case MDB_INVALID:
		return LDB_ERR_UNAVAILABLE;
	case MDB_BAD_TXN:
	case MDB_BAD_VALSIZE:
#ifdef MDB_BAD_DBI
	case MDB_BAD_DBI:
#endif
	case MDB_PANIC:
	case EINVAL:
		return LDB_ERR_PROTOCOL_ERROR;
	case MDB_MAP_FULL:
	case MDB_DBS_FULL:
	case MDB_READERS_FULL:
	case MDB_TLS_FULL:
	case MDB_TXN_FULL:
	case EAGAIN:
		return LDB_ERR_BUSY;
	case MDB_KEYEXIST:
		return LDB_ERR_ENTRY_ALREADY_EXISTS;
	case MDB_NOTFOUND:
	case ENOENT:
		return LDB_ERR_NO_SUCH_OBJECT;
	case EACCES:
		return LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS;
	default:
		break;
	}
	return LDB_ERR_OTHER;
}

#define ldb_mdb_error(ldb, ecode) lmdb_error_at(ldb, ecode, __FILE__, __LINE__)
static int lmdb_error_at(struct ldb_context *ldb,
			 int ecode,
			 const char *file,
			 int line)
{
	int ldb_err = ldb_mdb_err_map(ecode);
	char *reason = mdb_strerror(ecode);
	ldb_asprintf_errstring(ldb,
			       "(%d) - %s at %s:%d",
			       ecode,
			       reason,
			       file,
			       line);
	return ldb_err;
}

93 94

static bool lmdb_transaction_active(struct ltdb_private *ltdb)
95
{
96
	return ltdb->lmdb_private->txlist != NULL;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
}

static MDB_txn *lmdb_trans_get_tx(struct lmdb_trans *ltx)
{
	if (ltx == NULL) {
		return NULL;
	}

	return ltx->tx;
}

static void trans_push(struct lmdb_private *lmdb, struct lmdb_trans *ltx)
{
	if (lmdb->txlist) {
		talloc_steal(lmdb->txlist, ltx);
	}

	DLIST_ADD(lmdb->txlist, ltx);
}

static void trans_finished(struct lmdb_private *lmdb, struct lmdb_trans *ltx)
{
	DLIST_REMOVE(lmdb->txlist, ltx);
	talloc_free(ltx);
}


static struct lmdb_trans *lmdb_private_trans_head(struct lmdb_private *lmdb)
{
	struct lmdb_trans *ltx;

	ltx = lmdb->txlist;
	return ltx;
}


static MDB_txn *get_current_txn(struct lmdb_private *lmdb)
{
	MDB_txn *txn = NULL;

	txn = lmdb_trans_get_tx(lmdb_private_trans_head(lmdb));
	if (txn != NULL) {
		return txn;
	}
	if (lmdb->read_txn != NULL) {
		return lmdb->read_txn;
	}
	lmdb->error = MDB_BAD_TXN;
	ldb_set_errstring(lmdb->ldb, __location__":No active transaction\n");
	return NULL;
}

149
static int lmdb_store(struct ltdb_private *ltdb,
150
		      struct ldb_val key,
151
		      struct ldb_val data, int flags)
152
{
153
	struct lmdb_private *lmdb = ltdb->lmdb_private;
154 155 156 157 158 159
	MDB_val mdb_key;
	MDB_val mdb_data;
	int mdb_flags;
	MDB_txn *txn = NULL;
	MDB_dbi dbi = 0;

160
	if (ltdb->read_only) {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	txn = lmdb_trans_get_tx(lmdb_private_trans_head(lmdb));
	if (txn == NULL) {
		ldb_debug(lmdb->ldb, LDB_DEBUG_FATAL, "No transaction");
		lmdb->error = MDB_PANIC;
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	lmdb->error = mdb_dbi_open(txn, NULL, 0, &dbi);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	mdb_key.mv_size = key.length;
	mdb_key.mv_data = key.data;

	mdb_data.mv_size = data.length;
	mdb_data.mv_data = data.data;

	if (flags == TDB_INSERT) {
		mdb_flags = MDB_NOOVERWRITE;
	} else if ((flags == TDB_MODIFY)) {
		/*
		 * Modifying a record, ensure that it exists.
		 * This mimics the TDB semantics
		 */
		MDB_val value;
		lmdb->error = mdb_get(txn, dbi, &mdb_key, &value);
		if (lmdb->error != MDB_SUCCESS) {
			return ldb_mdb_error(lmdb->ldb, lmdb->error);
		}
		mdb_flags = 0;
	} else {
		mdb_flags = 0;
	}

	lmdb->error = mdb_put(txn, dbi, &mdb_key, &mdb_data, mdb_flags);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	return ldb_mdb_err_map(lmdb->error);
}

207
static int lmdb_delete(struct ltdb_private *ltdb, struct ldb_val key)
208
{
209
	struct lmdb_private *lmdb = ltdb->lmdb_private;
210 211 212 213
	MDB_val mdb_key;
	MDB_txn *txn = NULL;
	MDB_dbi dbi = 0;

214
	if (ltdb->read_only) {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	txn = lmdb_trans_get_tx(lmdb_private_trans_head(lmdb));
	if (txn == NULL) {
		ldb_debug(lmdb->ldb, LDB_DEBUG_FATAL, "No transaction");
		lmdb->error = MDB_PANIC;
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	lmdb->error = mdb_dbi_open(txn, NULL, 0, &dbi);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	mdb_key.mv_size = key.length;
	mdb_key.mv_data = key.data;

	lmdb->error = mdb_del(txn, dbi, &mdb_key, NULL);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}
	return ldb_mdb_err_map(lmdb->error);
}

240
static int lmdb_traverse_fn(struct ltdb_private *ltdb,
241 242 243
			    ldb_kv_traverse_fn fn,
			    void *ctx)
{
244
	struct lmdb_private *lmdb = ltdb->lmdb_private;
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
	MDB_val mdb_key;
	MDB_val mdb_data;
	MDB_txn *txn = NULL;
	MDB_dbi dbi = 0;
	MDB_cursor *cursor = NULL;
	int ret;

	txn = get_current_txn(lmdb);
	if (txn == NULL) {
		ldb_debug(lmdb->ldb, LDB_DEBUG_FATAL, "No transaction");
		lmdb->error = MDB_PANIC;
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	lmdb->error = mdb_dbi_open(txn, NULL, 0, &dbi);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	lmdb->error = mdb_cursor_open(txn, dbi, &cursor);
	if (lmdb->error != MDB_SUCCESS) {
		goto done;
	}

	while ((lmdb->error = mdb_cursor_get(
			cursor, &mdb_key,
			&mdb_data, MDB_NEXT)) == MDB_SUCCESS) {

		struct ldb_val key = {
			.length = mdb_key.mv_size,
			.data = mdb_key.mv_data,
		};
		struct ldb_val data = {
			.length = mdb_data.mv_size,
			.data = mdb_data.mv_data,
		};

282
		ret = fn(ltdb, key, data, ctx);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		if (ret != 0) {
			goto done;
		}
	}
	if (lmdb->error == MDB_NOTFOUND) {
		lmdb->error = MDB_SUCCESS;
	}
done:
	if (cursor != NULL) {
		mdb_cursor_close(cursor);
	}

	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}
	return ldb_mdb_err_map(lmdb->error);
}

301
static int lmdb_update_in_iterate(struct ltdb_private *ltdb,
302 303 304 305 306
				  struct ldb_val key,
				  struct ldb_val key2,
				  struct ldb_val data,
				  void *state)
{
307
	struct lmdb_private *lmdb = ltdb->lmdb_private;
308 309 310 311 312 313 314 315
	struct ldb_val copy;
	int ret = LDB_SUCCESS;

	/*
	 * Need to take a copy of the data as the delete operation alters the
	 * data, as it is in private lmdb memory.
	 */
	copy.length = data.length;
316
	copy.data = talloc_memdup(ltdb, data.data, data.length);
317 318 319 320 321
	if (copy.data == NULL) {
		lmdb->error = MDB_PANIC;
		return ldb_oom(lmdb->ldb);
	}

322
	lmdb->error = lmdb_delete(ltdb, key);
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	if (lmdb->error != MDB_SUCCESS) {
		ldb_debug(
			lmdb->ldb,
			LDB_DEBUG_ERROR,
			"Failed to delete %*.*s "
			"for rekey as %*.*s: %s",
			(int)key.length, (int)key.length,
			(const char *)key.data,
			(int)key2.length, (int)key2.length,
			(const char *)key.data,
			mdb_strerror(lmdb->error));
		ret = ldb_mdb_error(lmdb->ldb, lmdb->error);
		goto done;
	}

338
	lmdb->error = lmdb_store(ltdb, key2, copy, 0);
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	if (lmdb->error != MDB_SUCCESS) {
		ldb_debug(
			lmdb->ldb,
			LDB_DEBUG_ERROR,
			"Failed to rekey %*.*s as %*.*s: %s",
			(int)key.length, (int)key.length,
			(const char *)key.data,
			(int)key2.length, (int)key2.length,
			(const char *)key.data,
			mdb_strerror(lmdb->error));
		ret = ldb_mdb_error(lmdb->ldb, lmdb->error);
		goto done;
	}

done:
	if (copy.data != NULL) {
		TALLOC_FREE(copy.data);
		copy.length = 0;
	}

	/*
	 * Explicity invalidate the data, as the delete has done this
	 */
	data.length = 0;
	data.data = NULL;

	return ret;
}

/* Handles only a single record */
369 370
static int lmdb_parse_record(struct ltdb_private *ltdb, struct ldb_val key,
			     int (*parser)(struct ldb_val key, struct ldb_val data,
371 372 373
					   void *private_data),
			     void *ctx)
{
374
	struct lmdb_private *lmdb = ltdb->lmdb_private;
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
	MDB_val mdb_key;
	MDB_val mdb_data;
	MDB_txn *txn = NULL;
	MDB_dbi dbi;
	struct ldb_val data;

	txn = get_current_txn(lmdb);
	if (txn == NULL) {
		ldb_debug(lmdb->ldb, LDB_DEBUG_FATAL, "No transaction active");
		lmdb->error = MDB_PANIC;
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	lmdb->error = mdb_dbi_open(txn, NULL, 0, &dbi);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	mdb_key.mv_size = key.length;
	mdb_key.mv_data = key.data;

	lmdb->error = mdb_get(txn, dbi, &mdb_key, &mdb_data);
	if (lmdb->error != MDB_SUCCESS) {
		/* TODO closing a handle should not even be necessary */
		mdb_dbi_close(lmdb->env, dbi);
		if (lmdb->error == MDB_NOTFOUND) {
			return LDB_ERR_NO_SUCH_OBJECT;
		}
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}
	data.data = mdb_data.mv_data;
	data.length = mdb_data.mv_size;

	/* TODO closing a handle should not even be necessary */
	mdb_dbi_close(lmdb->env, dbi);

	return parser(key, data, ctx);
}


static int lmdb_lock_read(struct ldb_module *module)
{
	void *data = ldb_module_get_private(module);
418 419
	struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
	struct lmdb_private *lmdb = ltdb->lmdb_private;
420 421 422 423 424 425 426 427 428 429 430 431 432 433
	pid_t pid = getpid();

	if (pid != lmdb->pid) {
		ldb_asprintf_errstring(
			lmdb->ldb,
			__location__": Reusing ldb opened by pid %d in "
			"process %d\n",
			lmdb->pid,
			pid);
		lmdb->error = MDB_BAD_TXN;
		return LDB_ERR_PROTOCOL_ERROR;
	}

	lmdb->error = MDB_SUCCESS;
434 435
	if (lmdb_transaction_active(ltdb) == false &&
	    ltdb->read_lock_count == 0) {
436 437 438 439 440 441 442 443 444
		lmdb->error = mdb_txn_begin(lmdb->env,
					    NULL,
					    MDB_RDONLY,
					    &lmdb->read_txn);
	}
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

445
	ltdb->read_lock_count++;
446 447 448 449 450 451
	return ldb_mdb_err_map(lmdb->error);
}

static int lmdb_unlock_read(struct ldb_module *module)
{
	void *data = ldb_module_get_private(module);
452
	struct ltdb_private *ltdb = talloc_get_type(data, struct ltdb_private);
453

454 455
	if (lmdb_transaction_active(ltdb) == false && ltdb->read_lock_count == 1) {
		struct lmdb_private *lmdb = ltdb->lmdb_private;
456 457
		mdb_txn_commit(lmdb->read_txn);
		lmdb->read_txn = NULL;
458
		ltdb->read_lock_count--;
459 460
		return LDB_SUCCESS;
	}
461
	ltdb->read_lock_count--;
462 463 464
	return LDB_SUCCESS;
}

465
static int lmdb_transaction_start(struct ltdb_private *ltdb)
466
{
467
	struct lmdb_private *lmdb = ltdb->lmdb_private;
468 469 470 471 472 473
	struct lmdb_trans *ltx;
	struct lmdb_trans *ltx_head;
	MDB_txn *tx_parent;
	pid_t pid = getpid();

	/* Do not take out the transaction lock on a read-only DB */
474
	if (ltdb->read_only) {
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	ltx = talloc_zero(lmdb, struct lmdb_trans);
	if (ltx == NULL) {
		return ldb_oom(lmdb->ldb);
	}

	if (pid != lmdb->pid) {
		ldb_asprintf_errstring(
			lmdb->ldb,
			__location__": Reusing ldb opened by pid %d in "
			"process %d\n",
			lmdb->pid,
			pid);
		lmdb->error = MDB_BAD_TXN;
		return LDB_ERR_PROTOCOL_ERROR;
	}

	ltx_head = lmdb_private_trans_head(lmdb);

	tx_parent = lmdb_trans_get_tx(ltx_head);

	lmdb->error = mdb_txn_begin(lmdb->env, tx_parent, 0, &ltx->tx);
	if (lmdb->error != MDB_SUCCESS) {
		return ldb_mdb_error(lmdb->ldb, lmdb->error);
	}

	trans_push(lmdb, ltx);

	return ldb_mdb_err_map(lmdb->error);
}

508
static int lmdb_transaction_cancel(struct ltdb_private *ltdb)
509 510
{
	struct lmdb_trans *ltx;
511
	struct lmdb_private *lmdb = ltdb->lmdb_private;
512 513 514 515 516 517 518 519 520 521 522

	ltx = lmdb_private_trans_head(lmdb);
	if (ltx == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	mdb_txn_abort(ltx->tx);
	trans_finished(lmdb, ltx);
	return LDB_SUCCESS;
}

523
static int lmdb_transaction_prepare_commit(struct ltdb_private *ltdb)
524 525 526 527 528
{
	/* No need to prepare a commit */
	return LDB_SUCCESS;
}

529
static int lmdb_transaction_commit(struct ltdb_private *ltdb)
530 531
{
	struct lmdb_trans *ltx;
532
	struct lmdb_private *lmdb = ltdb->lmdb_private;
533 534 535 536 537 538 539 540 541 542 543 544

	ltx = lmdb_private_trans_head(lmdb);
	if (ltx == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	lmdb->error = mdb_txn_commit(ltx->tx);
	trans_finished(lmdb, ltx);

	return lmdb->error;
}

545
static int lmdb_error(struct ltdb_private *ltdb)
546
{
547
	return ldb_mdb_err_map(ltdb->lmdb_private->error);
548 549
}

550
static const char *lmdb_errorstr(struct ltdb_private *ltdb)
551
{
552
	return mdb_strerror(ltdb->lmdb_private->error);
553 554
}

555
static const char * lmdb_name(struct ltdb_private *ltdb)
556 557 558 559
{
	return "lmdb";
}

560
static bool lmdb_changed(struct ltdb_private *ltdb)
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 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 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 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 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
{
	/*
	 * lmdb does no provide a quick way to determine if the database
	 * has changed.  This function always returns true.
	 *
	 * Note that tdb uses a sequence number that allows this function
	 * to be implemented efficiently.
	 */
	return true;
}

static struct kv_db_ops lmdb_key_value_ops = {
	.store              = lmdb_store,
	.delete             = lmdb_delete,
	.iterate            = lmdb_traverse_fn,
	.update_in_iterate  = lmdb_update_in_iterate,
	.fetch_and_parse    = lmdb_parse_record,
	.lock_read          = lmdb_lock_read,
	.unlock_read        = lmdb_unlock_read,
	.begin_write        = lmdb_transaction_start,
	.prepare_write      = lmdb_transaction_prepare_commit,
	.finish_write       = lmdb_transaction_commit,
	.abort_write        = lmdb_transaction_cancel,
	.error              = lmdb_error,
	.errorstr           = lmdb_errorstr,
	.name               = lmdb_name,
	.has_changed        = lmdb_changed,
	.transaction_active = lmdb_transaction_active,
};

static const char *lmdb_get_path(const char *url)
{
	const char *path;

	/* parse the url */
	if (strchr(url, ':')) {
		if (strncmp(url, MDB_URL_PREFIX, MDB_URL_PREFIX_SIZE) != 0) {
			return NULL;
		}
		path = url + MDB_URL_PREFIX_SIZE;
	} else {
		path = url;
	}

	return path;
}

static int lmdb_pvt_destructor(struct lmdb_private *lmdb)
{
	struct lmdb_trans *ltx = NULL;

	/* Check if this is a forked child */
	if (getpid() != lmdb->pid) {
		int fd = 0;
		/*
		 * We cannot call mdb_env_close or commit any transactions,
		 * otherwise they might appear finished in the parent.
		 *
		 */

		if (mdb_env_get_fd(lmdb->env, &fd) == 0) {
			close(fd);
		}

		/* Remove the pointer, so that no access should occur */
		lmdb->env = NULL;

		return 0;
	}

	/*
	 * Close the read transaction if it's open
	 */
	if (lmdb->read_txn != NULL) {
		mdb_txn_abort(lmdb->read_txn);
	}

	if (lmdb->env == NULL) {
		return 0;
	}

	/*
	 * Abort any currently active transactions
	 */
	ltx = lmdb_private_trans_head(lmdb);
	while (ltx != NULL) {
		mdb_txn_abort(ltx->tx);
		trans_finished(lmdb, ltx);
		ltx = lmdb_private_trans_head(lmdb);
	}
	lmdb->env = NULL;

	return 0;
}

struct mdb_env_wrap {
	struct mdb_env_wrap *next, *prev;
	dev_t device;
	ino_t inode;
	MDB_env *env;
	pid_t pid;
};

static struct mdb_env_wrap *mdb_list;

/* destroy the last connection to an mdb */
static int mdb_env_wrap_destructor(struct mdb_env_wrap *w)
{
	mdb_env_close(w->env);
	DLIST_REMOVE(mdb_list, w);
	return 0;
}

static int lmdb_open_env(TALLOC_CTX *mem_ctx,
			 MDB_env **env,
			 struct ldb_context *ldb,
			 const char *path,
			 unsigned int flags)
{
	int ret;
	const size_t mmap_size = 8LL * GIGABYTE;
	unsigned int mdb_flags = MDB_NOSUBDIR|MDB_NOTLS;
	/*
	 * MDB_NOSUBDIR implies there is a separate file called path and a
	 * separate lockfile called path-lock
	 */

	struct mdb_env_wrap *w;
	struct stat st;
	pid_t pid = getpid();
	int fd = 0;
	unsigned v;

	if (stat(path, &st) == 0) {
		for (w=mdb_list;w;w=w->next) {
			if (st.st_dev == w->device &&
			    st.st_ino == w->inode &&
			    pid == w->pid) {
				/*
				 * We must have only one MDB_env per process
				 */
				if (!talloc_reference(mem_ctx, w)) {
					return ldb_oom(ldb);
				}
				*env = w->env;
				return LDB_SUCCESS;
			}
		}
	}

	w = talloc(mem_ctx, struct mdb_env_wrap);
	if (w == NULL) {
		return ldb_oom(ldb);
	}

	ret = mdb_env_create(env);
	if (ret != 0) {
		ldb_asprintf_errstring(
			ldb,
			"Could not create MDB environment %s: %s\n",
			path,
			mdb_strerror(ret));
		return ldb_mdb_err_map(ret);
	}

	/*
	 * Currently we set a 8Gb maximum database size
	 * via the constant mmap_size above
	 */
	ret = mdb_env_set_mapsize(*env, mmap_size);
	if (ret != 0) {
		ldb_asprintf_errstring(
			ldb,
			"Could not set MDB mmap() size to %llu on %s: %s\n",
			(unsigned long long)(mmap_size),
			path,
			mdb_strerror(ret));
		TALLOC_FREE(w);
		return ldb_mdb_err_map(ret);
	}

	mdb_env_set_maxreaders(*env, 100000);
	/*
	 * As we ensure that there is only one MDB_env open per database per
	 * process. We can not use the MDB_RDONLY flag, as another ldb may be
	 * opened in read write mode
	 */
	if (flags & LDB_FLG_NOSYNC) {
		mdb_flags |= MDB_NOSYNC;
	}
	ret = mdb_env_open(*env, path, mdb_flags, 0644);
	if (ret != 0) {
		ldb_asprintf_errstring(ldb,
				"Could not open DB %s: %s\n",
				path, mdb_strerror(ret));
		TALLOC_FREE(w);
		return ldb_mdb_err_map(ret);
	}

	ret = mdb_env_get_fd(*env, &fd);
	if (ret != 0) {
		ldb_asprintf_errstring(ldb,
				       "Could not obtain DB FD %s: %s\n",
				       path, mdb_strerror(ret));
		TALLOC_FREE(w);
		return ldb_mdb_err_map(ret);
	}

	/* Just as for TDB: on exec, don't inherit the fd */
	v = fcntl(fd, F_GETFD, 0);
	fcntl(fd, F_SETFD, v | FD_CLOEXEC);

	if (fstat(fd, &st) != 0) {
		ldb_asprintf_errstring(
			ldb,
			"Could not stat %s:\n",
			path);
		TALLOC_FREE(w);
		return LDB_ERR_OPERATIONS_ERROR;
	}
	w->env = *env;
	w->device = st.st_dev;
	w->inode  = st.st_ino;
	w->pid = pid;

	talloc_set_destructor(w, mdb_env_wrap_destructor);

	DLIST_ADD(mdb_list, w);

	return LDB_SUCCESS;

}

static int lmdb_pvt_open(struct lmdb_private *lmdb,
			 struct ldb_context *ldb,
			 const char *path,
			 unsigned int flags)
{
	int ret;
	int lmdb_max_key_length;

	if (flags & LDB_FLG_DONT_CREATE_DB) {
		struct stat st;
		if (stat(path, &st) != 0) {
			return LDB_ERR_UNAVAILABLE;
		}
	}

	ret = lmdb_open_env(lmdb, &lmdb->env, ldb, path, flags);
	if (ret != 0) {
		return ret;
	}

	/* Close when lmdb is released */
	talloc_set_destructor(lmdb, lmdb_pvt_destructor);

	/* Store the original pid during the LMDB open */
	lmdb->pid = getpid();

	lmdb_max_key_length = mdb_env_get_maxkeysize(lmdb->env);

	/* This will never happen, but if it does make sure to freak out */
	if (lmdb_max_key_length < LDB_MDB_MAX_KEY_LENGTH) {
		return ldb_operr(ldb);
	}

	return LDB_SUCCESS;
}

int lmdb_connect(struct ldb_context *ldb,
		 const char *url,
		 unsigned int flags,
		 const char *options[],
		 struct ldb_module **_module)
{
	const char *path = NULL;
	struct lmdb_private *lmdb = NULL;
838
	struct ltdb_private *ltdb = NULL;
839 840 841 842 843 844 845 846 847 848 849 850 851 852
	int ret;

	/*
	 * We hold locks, so we must use a private event context
	 * on each returned handle
	 */
	ldb_set_require_private_event_context(ldb);

	path = lmdb_get_path(url);
	if (path == NULL) {
		ldb_debug(ldb, LDB_DEBUG_ERROR, "Invalid mdb URL '%s'", url);
		return LDB_ERR_OPERATIONS_ERROR;
	}

853 854
	ltdb = talloc_zero(ldb, struct ltdb_private);
	if (!ltdb) {
855 856 857 858
		ldb_oom(ldb);
		return LDB_ERR_OPERATIONS_ERROR;
	}

859
	lmdb = talloc_zero(ltdb, struct lmdb_private);
860
	if (lmdb == NULL) {
861
		TALLOC_FREE(ltdb);
862 863 864
		return ldb_oom(ldb);
	}
	lmdb->ldb = ldb;
865
	ltdb->kv_ops = &lmdb_key_value_ops;
866 867 868

	ret = lmdb_pvt_open(lmdb, ldb, path, flags);
	if (ret != LDB_SUCCESS) {
869
		TALLOC_FREE(ltdb);
870 871 872
		return ret;
	}

873
	ltdb->lmdb_private = lmdb;
874
	if (flags & LDB_FLG_RDONLY) {
875
		ltdb->read_only = true;
876 877 878 879 880 881 882 883
	}

	/*
	 * This maximum length becomes encoded in the index values so
	 * must never change even if LMDB starts to allow longer keys.
	 * The override option is max_key_len_for_self_test, and is
	 * used for testing only.
	 */
884
	ltdb->max_key_length = LDB_MDB_MAX_KEY_LENGTH;
885

886
	return init_store(ltdb, "ldb_mdb backend", ldb, options, _module);
887
}