1 /* mdb.c - memory-mapped database library */
3 * Copyright 2011 Howard Chu, Symas Corp.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted only as authorized by the OpenLDAP
10 * A copy of this license is available in the file LICENSE in the
11 * top-level directory of the distribution or, alternatively, at
12 * <http://www.OpenLDAP.org/license.html>.
14 * This code is derived from btree.c written by Martin Hedenfalk.
16 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
18 * Permission to use, copy, modify, and distribute this software for any
19 * purpose with or without fee is hereby granted, provided that the above
20 * copyright notice and this permission notice appear in all copies.
22 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
23 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
25 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
27 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
28 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30 #include <sys/types.h>
32 #include <sys/queue.h>
33 #include <sys/param.h>
36 #ifdef HAVE_SYS_FILE_H
54 #define ULONG unsigned long
63 #if DEBUG && defined(__GNUC__)
64 # define DPRINTF(fmt, ...) \
65 fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
67 # define DPRINTF(...) ((void) 0)
72 #define MDB_MAGIC 0xBEEFC0DE
74 #define MAXKEYSIZE 511
76 #define P_INVALID (~0UL)
78 #define F_ISSET(w, f) (((w) & (f)) == (f))
80 typedef uint16_t indx_t;
82 #define DEFAULT_READERS 126
83 #define DEFAULT_MAPSIZE 1048576
85 /* Lock descriptor stuff */
87 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
90 typedef struct MDB_rxbody {
96 typedef struct MDB_reader {
99 #define mr_txnid mru.mrx.mrb_txnid
100 #define mr_pid mru.mrx.mrb_pid
101 #define mr_tid mru.mrx.mrb_tid
102 /* cache line alignment */
103 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
107 typedef struct MDB_txbody {
109 uint32_t mtb_version;
110 pthread_mutex_t mtb_mutex;
112 uint32_t mtb_numreaders;
115 typedef struct MDB_txninfo {
118 #define mti_magic mt1.mtb.mtb_magic
119 #define mti_version mt1.mtb.mtb_version
120 #define mti_mutex mt1.mtb.mtb_mutex
121 #define mti_txnid mt1.mtb.mtb_txnid
122 #define mti_numreaders mt1.mtb.mtb_numreaders
123 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
126 pthread_mutex_t mt2_wmutex;
127 #define mti_wmutex mt2.mt2_wmutex
128 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
130 MDB_reader mti_readers[1];
133 /* Common header for all page types. Overflow pages
134 * occupy a number of contiguous pages with no
135 * headers on any page after the first.
137 typedef struct MDB_page { /* represents a page of storage */
138 #define mp_pgno mp_p.p_pgno
140 pgno_t p_pgno; /* page number */
143 #define P_BRANCH 0x01 /* branch page */
144 #define P_LEAF 0x02 /* leaf page */
145 #define P_OVERFLOW 0x04 /* overflow page */
146 #define P_META 0x08 /* meta page */
147 #define P_DIRTY 0x10 /* dirty page */
148 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
150 #define mp_lower mp_pb.pb.pb_lower
151 #define mp_upper mp_pb.pb.pb_upper
152 #define mp_pages mp_pb.pb_pages
155 indx_t pb_lower; /* lower bound of free space */
156 indx_t pb_upper; /* upper bound of free space */
158 uint32_t pb_pages; /* number of overflow pages */
160 indx_t pb_ksize; /* on a LEAF2 page */
164 indx_t mp_ptrs[1]; /* dynamic size */
167 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
169 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
170 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
171 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
172 ((env)->me_psize - PAGEHDRSZ))
173 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
174 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
175 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
177 #define OVPAGES(size, psize) (PAGEHDRSZ + size + psize - 1) / psize;
179 typedef struct MDB_db {
183 ULONG md_branch_pages;
185 ULONG md_overflow_pages;
193 typedef struct MDB_meta { /* meta (footer) page content */
196 void *mm_address; /* address for fixed mapping */
197 size_t mm_mapsize; /* size of mmap region */
198 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
199 #define mm_psize mm_dbs[0].md_pad
200 #define mm_flags mm_dbs[0].md_flags
201 pgno_t mm_last_pg; /* last used page in file */
202 ULONG mm_txnid; /* txnid that committed this page */
205 typedef struct MDB_dhead { /* a dirty page */
207 unsigned md_pi; /* parent index */
211 typedef struct MDB_dpage {
216 typedef struct MDB_oldpages {
217 struct MDB_oldpages *mo_next;
219 pgno_t mo_pages[1]; /* dynamic */
222 typedef struct MDB_pageparent {
228 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
229 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
231 typedef struct MDB_ppage { /* ordered list of pages */
232 SLIST_ENTRY(MDB_ppage) mp_entry;
234 unsigned int mp_ki; /* cursor index on page */
236 SLIST_HEAD(page_stack, MDB_ppage);
238 /* FIXME: tree depth is mostly bounded, we should just
239 * use a fixed array and avoid malloc/pointer chasing
241 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
242 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
243 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
244 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
250 struct page_stack mc_stack; /* stack of parent pages */
252 short mc_initialized; /* 1 if initialized */
253 short mc_eof; /* 1 if end is reached */
254 struct MDB_xcursor *mc_xcursor;
257 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
259 typedef struct MDB_node {
260 #define mn_pgno mn_p.np_pgno
261 #define mn_dsize mn_p.np_dsize
263 pgno_t np_pgno; /* child page number */
264 uint32_t np_dsize; /* leaf data size */
266 unsigned int mn_flags:4;
267 unsigned int mn_ksize:12; /* key size */
268 #define F_BIGDATA 0x01 /* data put on overflow page */
269 #define F_SUBDATA 0x02 /* data is a sub-database */
273 typedef struct MDB_dbx {
275 MDB_cmp_func *md_cmp; /* user compare function */
276 MDB_cmp_func *md_dcmp; /* user dupsort function */
277 MDB_rel_func *md_rel; /* user relocate function */
279 unsigned int md_dirty;
283 pgno_t mt_next_pgno; /* next unallocated page */
287 pgno_t *mt_free_pgs; /* this is an IDL */
289 MIDL2 *dirty_list; /* modified pages */
292 MDB_dbx *mt_dbxs; /* array */
294 unsigned int mt_numdbs;
296 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
297 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
298 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
299 unsigned int mt_flags;
302 /* Context for sorted-dup records */
303 typedef struct MDB_xcursor {
304 MDB_cursor mx_cursor;
313 int me_mfd; /* just for writing the meta pages */
315 uint16_t me_db_toggle;
316 unsigned int me_psize;
317 unsigned int me_maxreaders;
318 unsigned int me_numdbs;
319 unsigned int me_maxdbs;
322 MDB_txninfo *me_txns;
323 MDB_meta *me_metas[2];
325 MDB_txn *me_txn; /* current write transaction */
327 off_t me_size; /* current file size */
328 MDB_dbx *me_dbxs; /* array */
330 MDB_oldpages *me_pghead;
331 pthread_key_t me_txkey; /* thread-key for readers */
332 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
333 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
336 #define NODESIZE offsetof(MDB_node, mn_data)
338 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
339 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
340 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
341 #define NODEKEY(node) (void *)((node)->mn_data)
342 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
343 #define NODEPGNO(node) ((node)->mn_pgno)
344 #define NODEDSZ(node) ((node)->mn_dsize)
346 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
348 static int mdb_search_page_root(MDB_txn *txn,
349 MDB_dbi dbi, MDB_val *key,
350 MDB_cursor *cursor, int modify,
351 MDB_pageparent *mpp);
352 static int mdb_search_page(MDB_txn *txn,
353 MDB_dbi dbi, MDB_val *key,
354 MDB_cursor *cursor, int modify,
355 MDB_pageparent *mpp);
357 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
358 static int mdb_env_read_meta(MDB_env *env, int *which);
359 static int mdb_env_write_meta(MDB_txn *txn);
360 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
362 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
363 MDB_val *key, int *exactp, unsigned int *kip);
364 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
365 indx_t indx, MDB_val *key, MDB_val *data,
366 pgno_t pgno, uint8_t flags);
367 static void mdb_del_node(MDB_page *mp, indx_t indx);
368 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
369 MDB_pageparent *mpp, MDB_node *leaf);
370 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
371 MDB_val *key, MDB_val *data, unsigned int flags);
372 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
374 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
375 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
376 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
377 MDB_pageparent *src, indx_t srcindx,
378 MDB_pageparent *dst, indx_t dstindx);
379 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
380 MDB_pageparent *dst);
381 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
382 unsigned int *newindxp, MDB_val *newkey,
383 MDB_val *newdata, pgno_t newpgno);
384 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
386 static void cursor_pop_page(MDB_cursor *cursor);
387 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
390 static int mdb_set_key(MDB_node *node, MDB_val *key);
391 static int mdb_sibling(MDB_cursor *cursor, int move_right);
392 static int mdb_cursor_next(MDB_cursor *cursor,
393 MDB_val *key, MDB_val *data, MDB_cursor_op op);
394 static int mdb_cursor_prev(MDB_cursor *cursor,
395 MDB_val *key, MDB_val *data, MDB_cursor_op op);
396 static int mdb_cursor_set(MDB_cursor *cursor,
397 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
398 static int mdb_cursor_first(MDB_cursor *cursor,
399 MDB_val *key, MDB_val *data);
400 static int mdb_cursor_last(MDB_cursor *cursor,
401 MDB_val *key, MDB_val *data);
403 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
404 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node);
405 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
407 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
409 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
411 static int memncmp(const void *s1, size_t n1,
412 const void *s2, size_t n2);
413 static int memnrcmp(const void *s1, size_t n1,
414 const void *s2, size_t n2);
417 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
419 int diff, len_diff = -1;
422 len_diff = (n1 > n2);
425 diff = memcmp(s1, s2, n1);
426 return diff ? diff : len_diff;
430 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
432 const unsigned char *p1, *p2, *p1_lim;
439 p1 = (const unsigned char *)s1 + n1 - 1;
440 p2 = (const unsigned char *)s2 + n2 - 1;
442 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
444 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
450 mdb_version(int *maj, int *min, int *pat)
452 *maj = MDB_VERSION_MAJOR;
453 *min = MDB_VERSION_MINOR;
454 *pat = MDB_VERSION_PATCH;
455 return MDB_VERSION_STRING;
459 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
461 return txn->mt_dbxs[dbi].md_cmp(a, b);
465 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
467 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
468 #if __BYTE_ORDER == __LITTLE_ENDIAN
472 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
474 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
477 /* Allocate new page(s) for writing */
479 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
482 pgno_t pgno = P_INVALID;
486 if (txn->mt_txnid > 2) {
488 oldest = txn->mt_txnid - 2;
489 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
490 /* See if there's anything in the free DB */
495 mpp.mp_parent = NULL;
497 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
498 leaf = NODEPTR(mpp.mp_page, 0);
499 kptr = (ULONG *)NODEKEY(leaf);
501 /* It's potentially usable, unless there are still
502 * older readers outstanding. Grab it.
504 if (oldest > *kptr) {
509 mdb_read_data(txn, leaf, &data);
510 idl = (ULONG *)data.mv_data;
511 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
512 mop->mo_next = txn->mt_env->me_pghead;
513 mop->mo_txnid = *kptr;
514 txn->mt_env->me_pghead = mop;
515 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
520 DPRINTF("IDL read txn %lu root %lu num %lu",
521 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
522 for (i=0; i<idl[0]; i++) {
523 DPRINTF("IDL %lu", idl[i+1]);
527 /* drop this IDL from the DB */
528 mpp.mp_parent = NULL;
530 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
531 leaf = NODEPTR(mpp.mp_page, 0);
532 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
535 if (txn->mt_env->me_pghead) {
537 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
538 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
541 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
543 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
544 MDB_oldpages *mop = txn->mt_env->me_pghead;
545 txn->mt_oldest = oldest;
547 /* FIXME: For now, always use fresh pages. We
548 * really ought to search the free list for a
553 /* peel pages off tail, so we only have to truncate the list */
554 pgno = MDB_IDL_LAST(mop->mo_pages);
555 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
557 if (mop->mo_pages[2] > mop->mo_pages[1])
558 mop->mo_pages[0] = 0;
562 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
563 txn->mt_env->me_pghead = mop->mo_next;
571 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
574 dp->h.md_parent = parent;
575 dp->h.md_pi = parent_idx;
576 if (pgno == P_INVALID) {
577 dp->p.mp_pgno = txn->mt_next_pgno;
578 txn->mt_next_pgno += num;
580 dp->p.mp_pgno = pgno;
582 mid.mid = dp->p.mp_pgno;
584 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
589 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
592 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
594 MDB_page *mp = pp->mp_page;
599 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
601 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
603 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
604 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
605 pgno = dp->p.mp_pgno;
606 memcpy(&dp->p, mp, txn->mt_env->me_psize);
609 mp->mp_flags |= P_DIRTY;
611 /* Update the page number to new touched page. */
612 if (pp->mp_parent != NULL)
613 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
620 mdb_env_sync(MDB_env *env, int force)
623 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
624 if (fdatasync(env->me_fd))
631 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
636 if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
637 DPRINTF("calloc: %s", strerror(errno));
642 txn->mt_flags |= MDB_TXN_RDONLY;
644 txn->mt_u.dirty_list = env->me_dirty_list;
645 txn->mt_u.dirty_list[0].mid = 0;
646 txn->mt_free_pgs = env->me_free_pgs;
647 txn->mt_free_pgs[0] = 0;
649 pthread_mutex_lock(&env->me_txns->mti_wmutex);
650 env->me_txns->mti_txnid++;
653 txn->mt_txnid = env->me_txns->mti_txnid;
655 MDB_reader *r = pthread_getspecific(env->me_txkey);
658 pthread_mutex_lock(&env->me_txns->mti_mutex);
659 for (i=0; i<env->me_txns->mti_numreaders; i++)
660 if (env->me_txns->mti_readers[i].mr_pid == 0)
662 if (i == env->me_maxreaders) {
663 pthread_mutex_unlock(&env->me_txns->mti_mutex);
666 env->me_txns->mti_readers[i].mr_pid = getpid();
667 env->me_txns->mti_readers[i].mr_tid = pthread_self();
668 r = &env->me_txns->mti_readers[i];
669 pthread_setspecific(env->me_txkey, r);
670 if (i >= env->me_txns->mti_numreaders)
671 env->me_txns->mti_numreaders = i+1;
672 pthread_mutex_unlock(&env->me_txns->mti_mutex);
674 r->mr_txnid = txn->mt_txnid;
675 txn->mt_u.reader = r;
682 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
687 /* Copy the DB arrays */
688 txn->mt_numdbs = env->me_numdbs;
689 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
690 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
691 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
692 if (txn->mt_numdbs > 2)
693 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
694 (txn->mt_numdbs - 2) * sizeof(MDB_db));
698 txn->mt_flags |= MDB_TXN_METOGGLE;
699 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
702 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
703 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
710 mdb_txn_abort(MDB_txn *txn)
718 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
719 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
723 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
724 txn->mt_u.reader->mr_txnid = 0;
729 /* Discard all dirty pages. */
730 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
731 free(txn->mt_u.dirty_list[i].mptr);
733 while ((mop = txn->mt_env->me_pghead)) {
734 txn->mt_env->me_pghead = mop->mo_next;
739 env->me_txns->mti_txnid--;
740 for (i=2; i<env->me_numdbs; i++)
741 env->me_dbxs[i].md_dirty = 0;
742 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
749 mdb_txn_commit(MDB_txn *txn)
758 struct iovec iov[MDB_COMMIT_PAGES];
761 assert(txn->mt_env != NULL);
765 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
766 DPRINTF("attempt to commit read-only transaction");
771 if (txn != env->me_txn) {
772 DPRINTF("attempt to commit unknown transaction");
777 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
778 DPRINTF("error flag is set, can't commit");
783 if (!txn->mt_u.dirty_list[0].mid)
786 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
787 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
789 /* should only be one record now */
790 if (env->me_pghead) {
794 mop = env->me_pghead;
795 key.mv_size = sizeof(pgno_t);
796 key.mv_data = (char *)&mop->mo_txnid;
797 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
798 data.mv_data = mop->mo_pages;
799 mdb_put0(txn, FREE_DBI, &key, &data, 0);
800 free(env->me_pghead);
801 env->me_pghead = NULL;
803 /* save to free list */
804 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
808 /* make sure last page of freeDB is touched and on freelist */
809 key.mv_size = MAXKEYSIZE+1;
811 mpp.mp_parent = NULL;
813 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
818 ULONG *idl = txn->mt_free_pgs;
819 DPRINTF("IDL write txn %lu root %lu num %lu",
820 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
821 for (i=0; i<idl[0]; i++) {
822 DPRINTF("IDL %lu", idl[i+1]);
826 /* write to last page of freeDB */
827 key.mv_size = sizeof(pgno_t);
828 key.mv_data = (char *)&txn->mt_txnid;
829 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
830 data.mv_data = txn->mt_free_pgs;
831 mdb_put0(txn, FREE_DBI, &key, &data, 0);
834 /* Update DB root pointers. Their pages have already been
835 * touched so this is all in-place and cannot fail.
839 data.mv_size = sizeof(MDB_db);
841 for (i = 2; i < txn->mt_numdbs; i++) {
842 if (txn->mt_dbxs[i].md_dirty) {
843 data.mv_data = &txn->mt_dbs[i];
844 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
849 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
856 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
857 dp = txn->mt_u.dirty_list[i].mptr;
858 if (dp->p.mp_pgno != next) {
860 DPRINTF("committing %u dirty pages", n);
861 rc = writev(env->me_fd, iov, n);
865 DPRINTF("short write, filesystem full?");
867 DPRINTF("writev: %s", strerror(errno));
874 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
875 next = dp->p.mp_pgno;
877 DPRINTF("committing page %lu", dp->p.mp_pgno);
878 iov[n].iov_len = env->me_psize * dp->h.md_num;
879 iov[n].iov_base = &dp->p;
880 size += iov[n].iov_len;
881 next = dp->p.mp_pgno + dp->h.md_num;
882 /* clear dirty flag */
883 dp->p.mp_flags &= ~P_DIRTY;
884 if (++n >= MDB_COMMIT_PAGES) {
893 DPRINTF("committing %u dirty pages", n);
894 rc = writev(env->me_fd, iov, n);
898 DPRINTF("short write, filesystem full?");
900 DPRINTF("writev: %s", strerror(errno));
907 /* Drop the dirty pages.
909 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
910 free(txn->mt_u.dirty_list[i].mptr);
912 if ((n = mdb_env_sync(env, 0)) != 0 ||
913 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
919 /* update the DB tables */
921 int toggle = !env->me_db_toggle;
923 for (i = 2; i < env->me_numdbs; i++) {
924 if (txn->mt_dbxs[i].md_dirty) {
925 env->me_dbs[toggle][i] = txn->mt_dbs[i];
926 txn->mt_dbxs[i].md_dirty = 0;
929 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
930 txn->mt_dbxs[i].md_dirty = 0;
931 env->me_dbxs[i] = txn->mt_dbxs[i];
932 env->me_dbs[toggle][i] = txn->mt_dbs[i];
934 env->me_db_toggle = toggle;
935 env->me_numdbs = txn->mt_numdbs;
940 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
951 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
960 /* We don't know the page size yet, so use a minimum value.
963 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
965 } else if (rc != PAGESIZE) {
968 DPRINTF("read: %s", strerror(errno));
972 p = (MDB_page *)page;
974 if (!F_ISSET(p->mp_flags, P_META)) {
975 DPRINTF("page %lu not a meta page", p->mp_pgno);
980 if (m->mm_magic != MDB_MAGIC) {
981 DPRINTF("meta has invalid magic");
985 if (m->mm_version != MDB_VERSION) {
986 DPRINTF("database is version %u, expected version %u",
987 m->mm_version, MDB_VERSION);
988 return MDB_VERSION_MISMATCH;
991 memcpy(meta, m, sizeof(*m));
996 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1003 DPRINTF("writing new meta page");
1004 psize = sysconf(_SC_PAGE_SIZE);
1006 meta->mm_magic = MDB_MAGIC;
1007 meta->mm_version = MDB_VERSION;
1008 meta->mm_psize = psize;
1009 meta->mm_last_pg = 1;
1010 meta->mm_flags = env->me_flags & 0xffff;
1011 meta->mm_flags |= MDB_INTEGERKEY;
1012 meta->mm_dbs[0].md_root = P_INVALID;
1013 meta->mm_dbs[1].md_root = P_INVALID;
1015 p = calloc(2, psize);
1017 p->mp_flags = P_META;
1020 memcpy(m, meta, sizeof(*meta));
1022 q = (MDB_page *)((char *)p + psize);
1025 q->mp_flags = P_META;
1028 memcpy(m, meta, sizeof(*meta));
1030 rc = write(env->me_fd, p, psize * 2);
1032 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1036 mdb_env_write_meta(MDB_txn *txn)
1044 assert(txn != NULL);
1045 assert(txn->mt_env != NULL);
1047 DPRINTF("writing meta page %d for root page %lu",
1048 !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE), txn->mt_dbs[MAIN_DBI].md_root);
1052 ptr = (char *)&meta;
1053 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1054 len = sizeof(MDB_meta) - off;
1057 meta.mm_dbs[0] = txn->mt_dbs[0];
1058 meta.mm_dbs[1] = txn->mt_dbs[1];
1059 meta.mm_last_pg = txn->mt_next_pgno - 1;
1060 meta.mm_txnid = txn->mt_txnid;
1062 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1063 off += env->me_psize;
1066 rc = pwrite(env->me_fd, ptr, len, off);
1068 DPRINTF("write failed, disk error?");
1076 mdb_env_read_meta(MDB_env *env, int *which)
1080 assert(env != NULL);
1082 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1085 if (env->me_meta != env->me_metas[toggle])
1086 env->me_meta = env->me_metas[toggle];
1090 DPRINTF("Using meta page %d", toggle);
1096 mdb_env_create(MDB_env **env)
1100 e = calloc(1, sizeof(MDB_env));
1101 if (!e) return ENOMEM;
1103 e->me_maxreaders = DEFAULT_READERS;
1113 mdb_env_set_mapsize(MDB_env *env, size_t size)
1117 env->me_mapsize = size;
1122 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1124 env->me_maxdbs = dbs;
1129 mdb_env_set_maxreaders(MDB_env *env, int readers)
1131 env->me_maxreaders = readers;
1136 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1138 if (!env || !readers)
1140 *readers = env->me_maxreaders;
1145 mdb_env_open2(MDB_env *env, unsigned int flags)
1151 env->me_flags = flags;
1153 memset(&meta, 0, sizeof(meta));
1155 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1158 DPRINTF("new mdbenv");
1162 if (!env->me_mapsize) {
1163 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1167 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1169 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1171 if (env->me_map == MAP_FAILED)
1175 meta.mm_mapsize = env->me_mapsize;
1176 if (flags & MDB_FIXEDMAP)
1177 meta.mm_address = env->me_map;
1178 i = mdb_env_init_meta(env, &meta);
1179 if (i != MDB_SUCCESS) {
1180 munmap(env->me_map, env->me_mapsize);
1184 env->me_psize = meta.mm_psize;
1186 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1187 env->me_metas[0] = METADATA(p);
1188 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1190 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1193 DPRINTF("opened database version %u, pagesize %u",
1194 env->me_meta->mm_version, env->me_psize);
1195 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1196 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1197 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1198 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1199 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1200 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1206 mdb_env_reader_dest(void *ptr)
1208 MDB_reader *reader = ptr;
1210 reader->mr_txnid = 0;
1215 /* downgrade the exclusive lock on the region back to shared */
1217 mdb_env_share_locks(MDB_env *env)
1219 struct flock lock_info;
1221 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1223 memset((void *)&lock_info, 0, sizeof(lock_info));
1224 lock_info.l_type = F_RDLCK;
1225 lock_info.l_whence = SEEK_SET;
1226 lock_info.l_start = 0;
1227 lock_info.l_len = 1;
1228 fcntl(env->me_lfd, F_SETLK, &lock_info);
1232 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1236 struct flock lock_info;
1240 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1244 /* Try to get exclusive lock. If we succeed, then
1245 * nobody is using the lock region and we should initialize it.
1247 memset((void *)&lock_info, 0, sizeof(lock_info));
1248 lock_info.l_type = F_WRLCK;
1249 lock_info.l_whence = SEEK_SET;
1250 lock_info.l_start = 0;
1251 lock_info.l_len = 1;
1252 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1256 lock_info.l_type = F_RDLCK;
1257 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1263 size = lseek(env->me_lfd, 0, SEEK_END);
1264 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1265 if (size < rsize && *excl) {
1266 if (ftruncate(env->me_lfd, rsize) != 0) {
1272 size = rsize - sizeof(MDB_txninfo);
1273 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1275 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1277 if (env->me_txns == MAP_FAILED) {
1282 pthread_mutexattr_t mattr;
1284 pthread_mutexattr_init(&mattr);
1285 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1289 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1290 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1291 env->me_txns->mti_version = MDB_VERSION;
1292 env->me_txns->mti_magic = MDB_MAGIC;
1293 env->me_txns->mti_txnid = 0;
1294 env->me_txns->mti_numreaders = 0;
1297 if (env->me_txns->mti_magic != MDB_MAGIC) {
1298 DPRINTF("lock region has invalid magic");
1302 if (env->me_txns->mti_version != MDB_VERSION) {
1303 DPRINTF("lock region is version %u, expected version %u",
1304 env->me_txns->mti_version, MDB_VERSION);
1305 rc = MDB_VERSION_MISMATCH;
1308 if (errno != EACCES && errno != EAGAIN) {
1322 #define LOCKNAME "/lock.mdb"
1323 #define DATANAME "/data.mdb"
1325 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1327 int oflags, rc, len, excl;
1328 char *lpath, *dpath;
1331 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1334 dpath = lpath + len + sizeof(LOCKNAME);
1335 sprintf(lpath, "%s" LOCKNAME, path);
1336 sprintf(dpath, "%s" DATANAME, path);
1338 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1342 if (F_ISSET(flags, MDB_RDONLY))
1345 oflags = O_RDWR | O_CREAT;
1347 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1352 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1353 /* synchronous fd for meta writes */
1354 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1356 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1361 env->me_path = strdup(path);
1362 DPRINTF("opened dbenv %p", (void *) env);
1363 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1365 mdb_env_share_locks(env);
1366 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1367 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1368 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1374 if (env->me_fd >= 0) {
1378 if (env->me_lfd >= 0) {
1388 mdb_env_close(MDB_env *env)
1393 free(env->me_dbs[1]);
1394 free(env->me_dbs[0]);
1398 pthread_key_delete(env->me_txkey);
1401 munmap(env->me_map, env->me_mapsize);
1406 pid_t pid = getpid();
1407 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1409 for (i=0; i<env->me_txns->mti_numreaders; i++)
1410 if (env->me_txns->mti_readers[i].mr_pid == pid)
1411 env->me_txns->mti_readers[i].mr_pid = 0;
1412 munmap(env->me_txns, size);
1418 /* Search for key within a leaf page, using binary search.
1419 * Returns the smallest entry larger or equal to the key.
1420 * If exactp is non-null, stores whether the found entry was an exact match
1421 * in *exactp (1 or 0).
1422 * If kip is non-null, stores the index of the found entry in *kip.
1423 * If no entry larger or equal to the key is found, returns NULL.
1426 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1427 int *exactp, unsigned int *kip)
1435 DPRINTF("searching %u keys in %s page %lu",
1437 IS_LEAF(mp) ? "leaf" : "branch",
1440 assert(NUMKEYS(mp) > 0);
1442 memset(&nodekey, 0, sizeof(nodekey));
1444 low = IS_LEAF(mp) ? 0 : 1;
1445 high = NUMKEYS(mp) - 1;
1446 while (low <= high) {
1447 i = (low + high) >> 1;
1448 node = NODEPTR(mp, i);
1450 nodekey.mv_size = node->mn_ksize;
1451 nodekey.mv_data = NODEKEY(node);
1453 if (txn->mt_dbxs[dbi].md_cmp)
1454 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1456 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1459 DPRINTF("found leaf index %u [%.*s], rc = %i",
1460 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1462 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1463 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1474 if (rc > 0) { /* Found entry is less than the key. */
1475 i++; /* Skip to get the smallest entry larger than key. */
1476 if (i >= NUMKEYS(mp))
1477 /* There is no entry larger or equal to the key. */
1481 *exactp = (rc == 0);
1482 if (kip) /* Store the key index if requested. */
1485 return NODEPTR(mp, i);
1489 cursor_pop_page(MDB_cursor *cursor)
1493 top = CURSOR_TOP(cursor);
1496 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1502 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1506 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1508 if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1510 ppage->mp_page = mp;
1511 CURSOR_PUSH(cursor, ppage);
1516 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1521 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1526 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1527 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1528 dp = txn->mt_u.dirty_list[x].mptr;
1534 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1536 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1542 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1543 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1545 MDB_page *mp = mpp->mp_page;
1548 if (cursor && cursor_push_page(cursor, mp) == NULL)
1551 while (IS_BRANCH(mp)) {
1555 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1556 assert(NUMKEYS(mp) > 1);
1557 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1559 if (key == NULL) /* Initialize cursor to first page. */
1561 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1562 /* cursor to last page */
1566 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1568 i = NUMKEYS(mp) - 1;
1576 DPRINTF("following index %u for key %.*s",
1577 i, (int)key->mv_size, (char *)key->mv_data);
1578 assert(i < NUMKEYS(mp));
1579 node = NODEPTR(mp, i);
1582 CURSOR_TOP(cursor)->mp_ki = i;
1584 mpp->mp_parent = mp;
1585 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1590 if (cursor && cursor_push_page(cursor, mp) == NULL)
1594 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1595 if ((rc = mdb_touch(txn, mpp)) != 0)
1597 dh = ((MDB_dhead *)mpp->mp_page)-1;
1598 dh->md_parent = mpp->mp_parent;
1599 dh->md_pi = mpp->mp_pi;
1606 DPRINTF("internal error, index points to a %02X page!?",
1611 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1612 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1617 /* Search for the page a given key should be in.
1618 * Stores a pointer to the found page in *mpp.
1619 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1620 * If cursor is non-null, pushes parent pages on the cursor stack.
1621 * If modify is true, visited pages are updated with new page numbers.
1624 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1625 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1630 /* Choose which root page to start with. If a transaction is given
1631 * use the root page from the transaction, otherwise read the last
1632 * committed root page.
1634 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1635 DPRINTF("transaction has failed, must abort");
1638 root = txn->mt_dbs[dbi].md_root;
1640 if (root == P_INVALID) { /* Tree is empty. */
1641 DPRINTF("tree is empty");
1642 return MDB_NOTFOUND;
1645 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1648 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1651 /* For sub-databases, update main root first */
1652 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1654 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1658 txn->mt_dbxs[dbi].md_dirty = 1;
1660 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1661 mpp->mp_parent = NULL;
1663 if ((rc = mdb_touch(txn, mpp)))
1665 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1669 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1673 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1675 MDB_page *omp; /* overflow mpage */
1678 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1679 data->mv_size = leaf->mn_dsize;
1680 data->mv_data = NODEDATA(leaf);
1684 /* Read overflow data.
1686 data->mv_size = leaf->mn_dsize;
1687 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1688 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1689 DPRINTF("read overflow page %lu failed", pgno);
1692 data->mv_data = omp;
1698 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1699 MDB_val *key, MDB_val *data)
1707 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1709 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1712 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1716 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1719 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1720 if (leaf && exact) {
1721 /* Return first duplicate data item */
1722 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1725 mdb_xcursor_init0(txn, dbi, &mx);
1726 mdb_xcursor_init1(txn, dbi, &mx, leaf);
1727 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1728 if (rc != MDB_SUCCESS)
1730 leaf = NODEPTR(mpp.mp_page, 0);
1732 rc = mdb_read_data(txn, leaf, data);
1741 mdb_sibling(MDB_cursor *cursor, int move_right)
1745 MDB_ppage *parent, *top;
1748 top = CURSOR_TOP(cursor);
1749 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1750 return MDB_NOTFOUND; /* root has no siblings */
1753 DPRINTF("parent page is page %lu, index %u",
1754 parent->mp_page->mp_pgno, parent->mp_ki);
1756 cursor_pop_page(cursor);
1757 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1758 : (parent->mp_ki == 0)) {
1759 DPRINTF("no more keys left, moving to %s sibling",
1760 move_right ? "right" : "left");
1761 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1763 parent = CURSOR_TOP(cursor);
1769 DPRINTF("just moving to %s index key %u",
1770 move_right ? "right" : "left", parent->mp_ki);
1772 assert(IS_BRANCH(parent->mp_page));
1774 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1775 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1778 mp->parent = parent->mp_page;
1779 mp->parent_index = parent->mp_ki;
1782 cursor_push_page(cursor, mp);
1788 mdb_set_key(MDB_node *node, MDB_val *key)
1793 key->mv_size = node->mn_ksize;
1794 key->mv_data = NODEKEY(node);
1800 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1807 if (cursor->mc_eof) {
1808 return MDB_NOTFOUND;
1811 assert(cursor->mc_initialized);
1813 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1814 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1815 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1816 if (op != MDB_NEXT || rc == MDB_SUCCESS)
1821 top = CURSOR_TOP(cursor);
1824 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1826 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1827 DPRINTF("=====> move to next sibling page");
1828 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1830 return MDB_NOTFOUND;
1832 top = CURSOR_TOP(cursor);
1834 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1838 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1839 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1841 assert(IS_LEAF(mp));
1842 leaf = NODEPTR(mp, top->mp_ki);
1845 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1848 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1849 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1850 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1851 if (rc != MDB_SUCCESS)
1856 return mdb_set_key(leaf, key);
1860 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1867 assert(cursor->mc_initialized);
1869 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1870 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1871 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1872 if (op != MDB_PREV || rc == MDB_SUCCESS)
1877 top = CURSOR_TOP(cursor);
1880 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1882 if (top->mp_ki == 0) {
1883 DPRINTF("=====> move to prev sibling page");
1884 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1885 return MDB_NOTFOUND;
1887 top = CURSOR_TOP(cursor);
1889 top->mp_ki = NUMKEYS(mp) - 1;
1890 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1896 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1897 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1899 assert(IS_LEAF(mp));
1900 leaf = NODEPTR(mp, top->mp_ki);
1903 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1906 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1907 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1908 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1909 if (rc != MDB_SUCCESS)
1914 return mdb_set_key(leaf, key);
1918 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1919 MDB_cursor_op op, int *exactp)
1928 assert(key->mv_size > 0);
1930 while (CURSOR_TOP(cursor) != NULL)
1931 cursor_pop_page(cursor);
1933 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1934 if (rc != MDB_SUCCESS)
1936 assert(IS_LEAF(mpp.mp_page));
1938 top = CURSOR_TOP(cursor);
1939 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1940 if (exactp != NULL && !*exactp) {
1941 /* MDB_SET specified and not an exact match. */
1942 return MDB_NOTFOUND;
1946 DPRINTF("===> inexact leaf not found, goto sibling");
1947 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1948 return rc; /* no entries matched */
1949 top = CURSOR_TOP(cursor);
1951 mpp.mp_page = top->mp_page;
1952 assert(IS_LEAF(mpp.mp_page));
1953 leaf = NODEPTR(mpp.mp_page, 0);
1956 cursor->mc_initialized = 1;
1960 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1963 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1964 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1965 if (op == MDB_SET || op == MDB_SET_RANGE) {
1966 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1970 if (op == MDB_GET_BOTH) {
1975 op2 = MDB_SET_RANGE;
1977 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
1978 if (rc != MDB_SUCCESS)
1984 rc = mdb_set_key(leaf, key);
1985 if (rc == MDB_SUCCESS) {
1986 DPRINTF("==> cursor placed on key %.*s",
1987 (int)key->mv_size, (char *)key->mv_data);
1995 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2001 while (CURSOR_TOP(cursor) != NULL)
2002 cursor_pop_page(cursor);
2004 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2005 if (rc != MDB_SUCCESS)
2007 assert(IS_LEAF(mpp.mp_page));
2009 leaf = NODEPTR(mpp.mp_page, 0);
2010 cursor->mc_initialized = 1;
2014 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2017 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2018 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2019 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2024 return mdb_set_key(leaf, key);
2028 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2036 while (CURSOR_TOP(cursor) != NULL)
2037 cursor_pop_page(cursor);
2039 lkey.mv_size = MAXKEYSIZE+1;
2040 lkey.mv_data = NULL;
2042 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2043 if (rc != MDB_SUCCESS)
2045 assert(IS_LEAF(mpp.mp_page));
2047 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2048 cursor->mc_initialized = 1;
2051 top = CURSOR_TOP(cursor);
2052 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2055 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2058 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2059 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2060 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2066 return mdb_set_key(leaf, key);
2070 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2080 case MDB_GET_BOTH_RANGE:
2088 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2090 } else if (op != MDB_SET_RANGE)
2091 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2093 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2097 case MDB_NEXT_NODUP:
2098 if (!cursor->mc_initialized)
2099 rc = mdb_cursor_first(cursor, key, data);
2101 rc = mdb_cursor_next(cursor, key, data, op);
2105 case MDB_PREV_NODUP:
2106 if (!cursor->mc_initialized || cursor->mc_eof)
2107 rc = mdb_cursor_last(cursor, key, data);
2109 rc = mdb_cursor_prev(cursor, key, data, op);
2112 rc = mdb_cursor_first(cursor, key, data);
2115 rc = mdb_cursor_last(cursor, key, data);
2118 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2126 /* Allocate a page and initialize it
2129 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2133 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2135 DPRINTF("allocated new mpage %lu, page size %u",
2136 dp->p.mp_pgno, txn->mt_env->me_psize);
2137 dp->p.mp_flags = flags | P_DIRTY;
2138 dp->p.mp_lower = PAGEHDRSZ;
2139 dp->p.mp_upper = txn->mt_env->me_psize;
2141 if (IS_BRANCH(&dp->p))
2142 txn->mt_dbs[dbi].md_branch_pages++;
2143 else if (IS_LEAF(&dp->p))
2144 txn->mt_dbs[dbi].md_leaf_pages++;
2145 else if (IS_OVERFLOW(&dp->p)) {
2146 txn->mt_dbs[dbi].md_overflow_pages += num;
2147 dp->p.mp_pages = num;
2154 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2158 sz = LEAFSIZE(key, data);
2159 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2160 /* put on overflow page */
2161 sz -= data->mv_size - sizeof(pgno_t);
2164 return sz + sizeof(indx_t);
2168 mdb_branch_size(MDB_env *env, MDB_val *key)
2173 if (sz >= env->me_psize / MDB_MINKEYS) {
2174 /* put on overflow page */
2175 /* not implemented */
2176 /* sz -= key->size - sizeof(pgno_t); */
2179 return sz + sizeof(indx_t);
2183 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2184 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2187 size_t node_size = NODESIZE;
2190 MDB_dpage *ofp = NULL; /* overflow page */
2192 assert(mp->mp_upper >= mp->mp_lower);
2194 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2195 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2196 IS_LEAF(mp) ? "leaf" : "branch",
2197 mp->mp_pgno, indx, key ? key->mv_size : 0);
2200 node_size += key->mv_size;
2204 if (F_ISSET(flags, F_BIGDATA)) {
2205 /* Data already on overflow page. */
2206 node_size += sizeof(pgno_t);
2207 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2208 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2209 /* Put data on overflow page. */
2210 DPRINTF("data size is %zu, put on overflow page",
2212 node_size += sizeof(pgno_t);
2213 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2215 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2218 node_size += data->mv_size;
2222 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2223 DPRINTF("not enough room in page %lu, got %u ptrs",
2224 mp->mp_pgno, NUMKEYS(mp));
2225 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2226 mp->mp_upper - mp->mp_lower);
2227 DPRINTF("node size = %zu", node_size);
2231 /* Move higher pointers up one slot. */
2232 for (i = NUMKEYS(mp); i > indx; i--)
2233 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2235 /* Adjust free space offsets. */
2236 ofs = mp->mp_upper - node_size;
2237 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2238 mp->mp_ptrs[indx] = ofs;
2240 mp->mp_lower += sizeof(indx_t);
2242 /* Write the node data. */
2243 node = NODEPTR(mp, indx);
2244 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2245 node->mn_flags = flags;
2247 node->mn_dsize = data->mv_size;
2249 node->mn_pgno = pgno;
2252 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2257 if (F_ISSET(flags, F_BIGDATA))
2258 memcpy(node->mn_data + key->mv_size, data->mv_data,
2261 memcpy(node->mn_data + key->mv_size, data->mv_data,
2264 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2266 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2274 mdb_del_node(MDB_page *mp, indx_t indx)
2277 indx_t i, j, numkeys, ptr;
2281 DPRINTF("delete node %u on %s page %lu", indx,
2282 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2283 assert(indx < NUMKEYS(mp));
2285 node = NODEPTR(mp, indx);
2286 sz = NODESIZE + node->mn_ksize;
2288 if (F_ISSET(node->mn_flags, F_BIGDATA))
2289 sz += sizeof(pgno_t);
2291 sz += NODEDSZ(node);
2294 ptr = mp->mp_ptrs[indx];
2295 numkeys = NUMKEYS(mp);
2296 for (i = j = 0; i < numkeys; i++) {
2298 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2299 if (mp->mp_ptrs[i] < ptr)
2300 mp->mp_ptrs[j] += sz;
2305 base = (char *)mp + mp->mp_upper;
2306 memmove(base + sz, base, ptr - mp->mp_upper);
2308 mp->mp_lower -= sizeof(indx_t);
2313 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2318 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2319 mx->mx_txn.mt_dbs = mx->mx_dbs;
2320 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2321 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2323 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2328 mx->mx_dbxs[dbn+1].md_parent = dbn;
2329 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2330 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2331 mx->mx_dbxs[dbn+1].md_dirty = 0;
2332 mx->mx_txn.mt_numdbs = dbn+2;
2334 SLIST_INIT(&mx->mx_cursor.mc_stack);
2335 mx->mx_cursor.mc_txn = &mx->mx_txn;
2336 mx->mx_cursor.mc_dbi = dbn+1;
2340 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2342 MDB_db *db = NODEDATA(node);
2344 mx->mx_dbs[0] = txn->mt_dbs[0];
2345 mx->mx_dbs[1] = txn->mt_dbs[1];
2347 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2352 mx->mx_dbs[dbn] = *db;
2353 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2354 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2355 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2356 mx->mx_txn.mt_oldest = txn->mt_oldest;
2357 mx->mx_txn.mt_u = txn->mt_u;
2361 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2363 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2364 txn->mt_oldest = mx->mx_txn.mt_oldest;
2365 txn->mt_u = mx->mx_txn.mt_u;
2366 txn->mt_dbs[0] = mx->mx_dbs[0];
2367 txn->mt_dbs[1] = mx->mx_dbs[1];
2368 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2369 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2371 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2372 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2377 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2380 size_t size = sizeof(MDB_cursor);
2382 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2385 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2386 size += sizeof(MDB_xcursor);
2388 if ((cursor = calloc(1, size)) != NULL) {
2389 SLIST_INIT(&cursor->mc_stack);
2390 cursor->mc_dbi = dbi;
2391 cursor->mc_txn = txn;
2392 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2393 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2394 cursor->mc_xcursor = mx;
2395 mdb_xcursor_init0(txn, dbi, mx);
2406 /* Return the count of duplicate data items for the current key */
2408 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2410 if (mc == NULL || countp == NULL)
2413 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2416 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2419 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2424 mdb_cursor_close(MDB_cursor *cursor)
2426 if (cursor != NULL) {
2427 while(!CURSOR_EMPTY(cursor))
2428 cursor_pop_page(cursor);
2429 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2430 mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2431 while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2432 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2440 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2442 indx_t ptr, i, numkeys;
2448 node = NODEPTR(mp, indx);
2449 ptr = mp->mp_ptrs[indx];
2450 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2452 (int)node->mn_ksize, (char *)NODEKEY(node),
2453 (int)key->mv_size, (char *)key->mv_data,
2456 delta = key->mv_size - node->mn_ksize;
2458 if (delta > 0 && SIZELEFT(mp) < delta) {
2459 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2463 numkeys = NUMKEYS(mp);
2464 for (i = 0; i < numkeys; i++) {
2465 if (mp->mp_ptrs[i] <= ptr)
2466 mp->mp_ptrs[i] -= delta;
2469 base = (char *)mp + mp->mp_upper;
2470 len = ptr - mp->mp_upper + NODESIZE;
2471 memmove(base - delta, base, len);
2472 mp->mp_upper -= delta;
2474 node = NODEPTR(mp, indx);
2475 node->mn_ksize = key->mv_size;
2478 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2483 /* Move a node from src to dst.
2486 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2487 MDB_pageparent *dst, indx_t dstindx)
2493 srcnode = NODEPTR(src->mp_page, srcindx);
2494 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2495 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2497 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2498 src->mp_page->mp_pgno,
2499 dstindx, dst->mp_page->mp_pgno);
2501 /* Mark src and dst as dirty. */
2502 if ((rc = mdb_touch(txn, src)) ||
2503 (rc = mdb_touch(txn, dst)))
2506 /* Add the node to the destination page.
2508 key.mv_size = srcnode->mn_ksize;
2509 key.mv_data = NODEKEY(srcnode);
2510 data.mv_size = NODEDSZ(srcnode);
2511 data.mv_data = NODEDATA(srcnode);
2512 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2514 if (rc != MDB_SUCCESS)
2517 /* Delete the node from the source page.
2519 mdb_del_node(src->mp_page, srcindx);
2521 /* Update the parent separators.
2523 if (srcindx == 0 && src->mp_pi != 0) {
2524 DPRINTF("update separator for source page %lu to [%.*s]",
2525 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2526 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2527 &key)) != MDB_SUCCESS)
2531 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2533 nullkey.mv_size = 0;
2534 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2537 if (dstindx == 0 && dst->mp_pi != 0) {
2538 DPRINTF("update separator for destination page %lu to [%.*s]",
2539 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2540 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2541 &key)) != MDB_SUCCESS)
2545 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2547 nullkey.mv_size = 0;
2548 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2555 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2564 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2566 assert(txn != NULL);
2567 assert(src->mp_parent); /* can't merge root page */
2568 assert(dst->mp_parent);
2570 /* Mark src and dst as dirty. */
2571 if ((rc = mdb_touch(txn, src)) ||
2572 (rc = mdb_touch(txn, dst)))
2575 /* Move all nodes from src to dst.
2577 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2578 srcnode = NODEPTR(src->mp_page, i);
2580 key.mv_size = srcnode->mn_ksize;
2581 key.mv_data = NODEKEY(srcnode);
2582 data.mv_size = NODEDSZ(srcnode);
2583 data.mv_data = NODEDATA(srcnode);
2584 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2585 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2586 if (rc != MDB_SUCCESS)
2590 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2591 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2593 /* Unlink the src page from parent.
2595 mdb_del_node(src->mp_parent, src->mp_pi);
2596 if (src->mp_pi == 0) {
2598 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2602 if (IS_LEAF(src->mp_page))
2603 txn->mt_dbs[dbi].md_leaf_pages--;
2605 txn->mt_dbs[dbi].md_branch_pages--;
2607 mpp.mp_page = src->mp_parent;
2608 dh = (MDB_dhead *)src->mp_parent;
2610 mpp.mp_parent = dh->md_parent;
2611 mpp.mp_pi = dh->md_pi;
2613 return mdb_rebalance(txn, dbi, &mpp);
2616 #define FILL_THRESHOLD 250
2619 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2624 indx_t si = 0, di = 0;
2626 assert(txn != NULL);
2627 assert(mpp != NULL);
2629 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2630 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2631 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2633 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2634 DPRINTF("no need to rebalance page %lu, above fill threshold",
2635 mpp->mp_page->mp_pgno);
2639 if (mpp->mp_parent == NULL) {
2640 if (NUMKEYS(mpp->mp_page) == 0) {
2641 DPRINTF("tree is completely empty");
2642 txn->mt_dbs[dbi].md_root = P_INVALID;
2643 txn->mt_dbs[dbi].md_depth--;
2644 txn->mt_dbs[dbi].md_leaf_pages--;
2645 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2646 DPRINTF("collapsing root page!");
2647 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2648 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2650 txn->mt_dbs[dbi].md_depth--;
2651 txn->mt_dbs[dbi].md_branch_pages--;
2653 DPRINTF("root page doesn't need rebalancing");
2657 /* The parent (branch page) must have at least 2 pointers,
2658 * otherwise the tree is invalid.
2660 assert(NUMKEYS(mpp->mp_parent) > 1);
2662 /* Leaf page fill factor is below the threshold.
2663 * Try to move keys from left or right neighbor, or
2664 * merge with a neighbor page.
2669 if (mpp->mp_pi == 0) {
2670 /* We're the leftmost leaf in our parent.
2672 DPRINTF("reading right neighbor");
2673 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2674 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2676 npp.mp_pi = mpp->mp_pi + 1;
2678 di = NUMKEYS(mpp->mp_page);
2680 /* There is at least one neighbor to the left.
2682 DPRINTF("reading left neighbor");
2683 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2684 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2686 npp.mp_pi = mpp->mp_pi - 1;
2687 si = NUMKEYS(npp.mp_page) - 1;
2690 npp.mp_parent = mpp->mp_parent;
2692 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2693 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2695 /* If the neighbor page is above threshold and has at least two
2696 * keys, move one key from it.
2698 * Otherwise we should try to merge them.
2700 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2701 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2702 else { /* FIXME: if (has_enough_room()) */
2703 if (mpp->mp_pi == 0)
2704 return mdb_merge(txn, dbi, &npp, mpp);
2706 return mdb_merge(txn, dbi, mpp, &npp);
2711 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2715 /* add overflow pages to free list */
2716 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2720 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2721 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2722 for (i=0; i<ovpages; i++) {
2723 DPRINTF("freed ov page %lu", pg);
2724 mdb_midl_insert(txn->mt_free_pgs, pg);
2728 mdb_del_node(mpp->mp_page, ki);
2729 txn->mt_dbs[dbi].md_entries--;
2730 rc = mdb_rebalance(txn, dbi, mpp);
2731 if (rc != MDB_SUCCESS)
2732 txn->mt_flags |= MDB_TXN_ERROR;
2738 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2739 MDB_val *key, MDB_val *data,
2747 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2749 assert(key != NULL);
2751 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2754 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2758 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2762 mpp.mp_parent = NULL;
2764 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2767 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2768 if (leaf == NULL || !exact) {
2769 return MDB_NOTFOUND;
2772 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2776 mdb_xcursor_init0(txn, dbi, &mx);
2777 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2778 if (flags == MDB_DEL_DUP) {
2779 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2780 mdb_xcursor_fini(txn, dbi, &mx);
2781 if (rc != MDB_SUCCESS)
2783 /* If sub-DB still has entries, we're done */
2784 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2785 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2789 /* otherwise fall thru and delete the sub-DB */
2791 /* add all the child DB's pages to the free list */
2792 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2793 NULL, &mx.mx_cursor, 0, &mp2);
2794 if (rc == MDB_SUCCESS) {
2795 MDB_ppage *top, *parent;
2799 cursor_pop_page(&mx.mx_cursor);
2800 top = CURSOR_TOP(&mx.mx_cursor);
2802 parent = SLIST_NEXT(top, mp_entry);
2803 while (parent != NULL) {
2804 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2805 ni = NODEPTR(top->mp_page, i);
2806 mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2810 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2811 cursor_pop_page(&mx.mx_cursor);
2812 top = CURSOR_TOP(&mx.mx_cursor);
2813 parent = SLIST_NEXT(top, mp_entry);
2815 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2816 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2821 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2826 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2829 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2832 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2833 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2834 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2835 * refer to a node in the new right sibling page.
2838 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2839 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2842 int rc = MDB_SUCCESS, ins_new = 0;
2845 unsigned int i, j, split_indx;
2847 MDB_val sepkey, rkey, rdata;
2849 MDB_dpage *mdp, *rdp, *pdp;
2852 assert(txn != NULL);
2854 dh = ((MDB_dhead *)*mpp) - 1;
2855 mdp = (MDB_dpage *)dh;
2856 newindx = *newindxp;
2858 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2859 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2860 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2862 if (mdp->h.md_parent == NULL) {
2863 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2866 mdp->h.md_parent = &pdp->p;
2867 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2868 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2869 txn->mt_dbs[dbi].md_depth++;
2871 /* Add left (implicit) pointer. */
2872 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2873 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2876 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2879 /* Create a right sibling. */
2880 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2882 rdp->h.md_parent = mdp->h.md_parent;
2883 rdp->h.md_pi = mdp->h.md_pi + 1;
2884 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2886 /* Move half of the keys to the right sibling. */
2887 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2889 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2890 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2891 mdp->p.mp_lower = PAGEHDRSZ;
2892 mdp->p.mp_upper = txn->mt_env->me_psize;
2894 split_indx = NUMKEYS(copy) / 2 + 1;
2896 /* First find the separating key between the split pages.
2898 memset(&sepkey, 0, sizeof(sepkey));
2899 if (newindx == split_indx) {
2900 sepkey.mv_size = newkey->mv_size;
2901 sepkey.mv_data = newkey->mv_data;
2903 node = NODEPTR(copy, split_indx);
2904 sepkey.mv_size = node->mn_ksize;
2905 sepkey.mv_data = NODEKEY(node);
2908 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2910 /* Copy separator key to the parent.
2912 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2913 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2914 &sepkey, NULL, rdp->p.mp_pgno);
2916 /* Right page might now have changed parent.
2917 * Check if left page also changed parent.
2919 if (rdp->h.md_parent != mdp->h.md_parent &&
2920 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2921 mdp->h.md_parent = rdp->h.md_parent;
2922 mdp->h.md_pi = rdp->h.md_pi - 1;
2925 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2926 &sepkey, NULL, rdp->p.mp_pgno, 0);
2928 if (rc != MDB_SUCCESS) {
2933 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2934 if (i < split_indx) {
2935 /* Re-insert in left sibling. */
2938 /* Insert in right sibling. */
2939 if (i == split_indx)
2940 /* Reset insert index for right sibling. */
2941 j = (i == newindx && ins_new);
2945 if (i == newindx && !ins_new) {
2946 /* Insert the original entry that caused the split. */
2947 rkey.mv_data = newkey->mv_data;
2948 rkey.mv_size = newkey->mv_size;
2949 if (IS_LEAF(&mdp->p)) {
2950 rdata.mv_data = newdata->mv_data;
2951 rdata.mv_size = newdata->mv_size;
2958 /* Update page and index for the new key. */
2961 } else if (i == NUMKEYS(copy)) {
2964 node = NODEPTR(copy, i);
2965 rkey.mv_data = NODEKEY(node);
2966 rkey.mv_size = node->mn_ksize;
2967 if (IS_LEAF(&mdp->p)) {
2968 rdata.mv_data = NODEDATA(node);
2969 rdata.mv_size = node->mn_dsize;
2971 pgno = node->mn_pgno;
2972 flags = node->mn_flags;
2977 if (!IS_LEAF(&mdp->p) && j == 0) {
2978 /* First branch index doesn't need key data. */
2982 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2990 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
2991 MDB_val *key, MDB_val *data, unsigned int flags)
2993 int rc = MDB_SUCCESS, exact;
2997 MDB_val xdata, *rdata;
3000 DPRINTF("==> put key %.*s, size %zu, data size %zu",
3001 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
3003 mpp.mp_parent = NULL;
3005 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3006 if (rc == MDB_SUCCESS) {
3007 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3008 if (leaf && exact) {
3009 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3012 if (flags == MDB_NOOVERWRITE) {
3013 DPRINTF("duplicate key %.*s",
3014 (int)key->mv_size, (char *)key->mv_data);
3015 return MDB_KEYEXIST;
3017 /* same size, just replace it */
3018 if (NODEDSZ(leaf) == data->mv_size) {
3019 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3022 mdb_del_node(mpp.mp_page, ki);
3024 if (leaf == NULL) { /* append if not found */
3025 ki = NUMKEYS(mpp.mp_page);
3026 DPRINTF("appending key at index %i", ki);
3028 } else if (rc == MDB_NOTFOUND) {
3030 /* new file, just write a root leaf page */
3031 DPRINTF("allocating new root leaf page");
3032 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3035 mpp.mp_page = &dp->p;
3036 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3037 txn->mt_dbs[dbi].md_depth++;
3043 assert(IS_LEAF(mpp.mp_page));
3044 DPRINTF("there are %u keys, should insert new key at index %i",
3045 NUMKEYS(mpp.mp_page), ki);
3047 /* For sorted dups, the data item at this level is a DB record
3048 * for a child DB; the actual data elements are stored as keys
3051 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3053 xdata.mv_size = sizeof(MDB_db);
3054 xdata.mv_data = &dummy;
3055 memset(&dummy, 0, sizeof(dummy));
3056 dummy.md_root = P_INVALID;
3061 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3062 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3064 /* There is room already in this leaf page. */
3065 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3068 if (rc != MDB_SUCCESS)
3069 txn->mt_flags |= MDB_TXN_ERROR;
3071 txn->mt_dbs[dbi].md_entries++;
3073 /* Remember if we just added a subdatabase */
3074 if (flags & F_SUBDATA) {
3075 leaf = NODEPTR(mpp.mp_page, ki);
3076 leaf->mn_flags |= F_SUBDATA;
3079 /* Now store the actual data in the child DB. Note that we're
3080 * storing the user data in the keys field, so there are strict
3081 * size limits on dupdata. The actual data fields of the child
3082 * DB are all zero size.
3084 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3087 leaf = NODEPTR(mpp.mp_page, ki);
3089 mdb_xcursor_init0(txn, dbi, &mx);
3090 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3093 if (flags == MDB_NODUPDATA)
3094 flags = MDB_NOOVERWRITE;
3095 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3096 mdb_xcursor_fini(txn, dbi, &mx);
3097 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3107 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3108 MDB_val *key, MDB_val *data, unsigned int flags)
3110 assert(key != NULL);
3111 assert(data != NULL);
3113 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3116 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3120 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3124 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3127 return mdb_put0(txn, dbi, key, data, flags);
3131 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3136 *arg = env->me_flags;
3141 mdb_env_get_path(MDB_env *env, const char **arg)
3146 *arg = env->me_path;
3151 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3153 arg->ms_psize = env->me_psize;
3154 arg->ms_depth = db->md_depth;
3155 arg->ms_branch_pages = db->md_branch_pages;
3156 arg->ms_leaf_pages = db->md_leaf_pages;
3157 arg->ms_overflow_pages = db->md_overflow_pages;
3158 arg->ms_entries = db->md_entries;
3163 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3165 if (env == NULL || arg == NULL)
3168 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3171 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3181 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3182 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3186 /* Is the DB already open? */
3188 for (i=2; i<txn->mt_numdbs; i++) {
3189 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3190 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3196 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3199 /* Find the DB info */
3201 key.mv_data = (void *)name;
3202 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3204 /* Create if requested */
3205 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3207 data.mv_size = sizeof(MDB_db);
3208 data.mv_data = &dummy;
3209 memset(&dummy, 0, sizeof(dummy));
3210 dummy.md_root = P_INVALID;
3211 dummy.md_flags = flags & 0xffff;
3212 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3216 /* OK, got info, add to table */
3217 if (rc == MDB_SUCCESS) {
3218 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3219 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3220 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3221 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3222 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3223 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3224 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3225 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3226 *dbi = txn->mt_numdbs;
3233 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3235 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3238 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3241 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3244 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3246 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3247 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3248 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3252 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3254 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3257 txn->mt_dbxs[dbi].md_cmp = cmp;
3261 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3263 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3266 txn->mt_dbxs[dbi].md_dcmp = cmp;
3270 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3272 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3275 txn->mt_dbxs[dbi].md_rel = rel;