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 */
206 STAILQ_ENTRY(MDB_dpage) md_next; /* queue of dirty pages */
208 unsigned md_pi; /* parent index */
212 typedef struct MDB_dpage {
217 STAILQ_HEAD(dirty_queue, MDB_dpage); /* FIXME: use a sorted data structure */
219 typedef struct MDB_oldpages {
220 struct MDB_oldpages *mo_next;
222 pgno_t mo_pages[1]; /* dynamic */
225 typedef struct MDB_pageparent {
231 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
232 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
234 typedef struct MDB_ppage { /* ordered list of pages */
235 SLIST_ENTRY(MDB_ppage) mp_entry;
237 unsigned int mp_ki; /* cursor index on page */
239 SLIST_HEAD(page_stack, MDB_ppage);
241 /* FIXME: tree depth is mostly bounded, we should just
242 * use a fixed array and avoid malloc/pointer chasing
244 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
245 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
246 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
247 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
253 struct page_stack mc_stack; /* stack of parent pages */
255 short mc_initialized; /* 1 if initialized */
256 short mc_eof; /* 1 if end is reached */
257 struct MDB_xcursor *mc_xcursor;
260 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
262 typedef struct MDB_node {
263 #define mn_pgno mn_p.np_pgno
264 #define mn_dsize mn_p.np_dsize
266 pgno_t np_pgno; /* child page number */
267 uint32_t np_dsize; /* leaf data size */
269 unsigned int mn_flags:4;
270 unsigned int mn_ksize:12; /* key size */
271 #define F_BIGDATA 0x01 /* data put on overflow page */
272 #define F_SUBDATA 0x02 /* data is a sub-database */
276 typedef struct MDB_dbx {
278 MDB_cmp_func *md_cmp; /* user compare function */
279 MDB_cmp_func *md_dcmp; /* user dupsort function */
280 MDB_rel_func *md_rel; /* user relocate function */
282 unsigned int md_dirty;
286 pgno_t mt_next_pgno; /* next unallocated page */
290 pgno_t *mt_free_pgs; /* this is an IDL */
292 struct dirty_queue *dirty_queue; /* modified pages */
295 MDB_dbx *mt_dbxs; /* array */
297 unsigned int mt_numdbs;
299 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
300 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
301 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
302 unsigned int mt_flags;
305 /* Context for sorted-dup records */
306 typedef struct MDB_xcursor {
307 MDB_cursor mx_cursor;
316 int me_mfd; /* just for writing the meta pages */
318 uint16_t me_db_toggle;
319 unsigned int me_psize;
320 unsigned int me_maxreaders;
321 unsigned int me_numdbs;
322 unsigned int me_maxdbs;
325 MDB_txninfo *me_txns;
326 MDB_meta *me_metas[2];
328 MDB_txn *me_txn; /* current write transaction */
330 off_t me_size; /* current file size */
331 MDB_dbx *me_dbxs; /* array */
333 MDB_oldpages *me_pghead;
334 pthread_key_t me_txkey; /* thread-key for readers */
335 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
338 #define NODESIZE offsetof(MDB_node, mn_data)
340 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
341 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
342 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
343 #define NODEKEY(node) (void *)((node)->mn_data)
344 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
345 #define NODEPGNO(node) ((node)->mn_pgno)
346 #define NODEDSZ(node) ((node)->mn_dsize)
348 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
350 static int mdb_search_page_root(MDB_txn *txn,
351 MDB_dbi dbi, MDB_val *key,
352 MDB_cursor *cursor, int modify,
353 MDB_pageparent *mpp);
354 static int mdb_search_page(MDB_txn *txn,
355 MDB_dbi dbi, MDB_val *key,
356 MDB_cursor *cursor, int modify,
357 MDB_pageparent *mpp);
359 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
360 static int mdb_env_read_meta(MDB_env *env, int *which);
361 static int mdb_env_write_meta(MDB_txn *txn);
362 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
364 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
365 MDB_val *key, int *exactp, unsigned int *kip);
366 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
367 indx_t indx, MDB_val *key, MDB_val *data,
368 pgno_t pgno, uint8_t flags);
369 static void mdb_del_node(MDB_page *mp, indx_t indx);
370 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
371 MDB_pageparent *mpp, MDB_node *leaf);
372 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
373 MDB_val *key, MDB_val *data, unsigned int flags);
374 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
376 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
377 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
378 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
379 MDB_pageparent *src, indx_t srcindx,
380 MDB_pageparent *dst, indx_t dstindx);
381 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
382 MDB_pageparent *dst);
383 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
384 unsigned int *newindxp, MDB_val *newkey,
385 MDB_val *newdata, pgno_t newpgno);
386 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
388 static void cursor_pop_page(MDB_cursor *cursor);
389 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
392 static int mdb_set_key(MDB_node *node, MDB_val *key);
393 static int mdb_sibling(MDB_cursor *cursor, int move_right);
394 static int mdb_cursor_next(MDB_cursor *cursor,
395 MDB_val *key, MDB_val *data, MDB_cursor_op op);
396 static int mdb_cursor_prev(MDB_cursor *cursor,
397 MDB_val *key, MDB_val *data, MDB_cursor_op op);
398 static int mdb_cursor_set(MDB_cursor *cursor,
399 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
400 static int mdb_cursor_first(MDB_cursor *cursor,
401 MDB_val *key, MDB_val *data);
402 static int mdb_cursor_last(MDB_cursor *cursor,
403 MDB_val *key, MDB_val *data);
405 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
406 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node);
407 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
409 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
411 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
413 static int memncmp(const void *s1, size_t n1,
414 const void *s2, size_t n2);
415 static int memnrcmp(const void *s1, size_t n1,
416 const void *s2, size_t n2);
419 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
421 int diff, len_diff = -1;
424 len_diff = (n1 > n2);
427 diff = memcmp(s1, s2, n1);
428 return diff ? diff : len_diff;
432 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
434 const unsigned char *p1, *p2, *p1_lim;
441 p1 = (const unsigned char *)s1 + n1 - 1;
442 p2 = (const unsigned char *)s2 + n2 - 1;
444 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
446 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
452 mdb_version(int *maj, int *min, int *pat)
454 *maj = MDB_VERSION_MAJOR;
455 *min = MDB_VERSION_MINOR;
456 *pat = MDB_VERSION_PATCH;
457 return MDB_VERSION_STRING;
461 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
463 return txn->mt_dbxs[dbi].md_cmp(a, b);
467 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
469 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
470 #if __BYTE_ORDER == __LITTLE_ENDIAN
474 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
476 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
479 /* Allocate new page(s) for writing */
481 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
484 pgno_t pgno = P_INVALID;
487 if (txn->mt_txnid > 2) {
489 oldest = txn->mt_txnid - 2;
490 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
491 /* See if there's anything in the free DB */
496 mpp.mp_parent = NULL;
498 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
499 leaf = NODEPTR(mpp.mp_page, 0);
500 kptr = (ULONG *)NODEKEY(leaf);
502 /* It's potentially usable, unless there are still
503 * older readers outstanding. Grab it.
505 if (oldest > *kptr) {
510 mdb_read_data(txn, leaf, &data);
511 idl = (ULONG *)data.mv_data;
512 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
513 mop->mo_next = txn->mt_env->me_pghead;
514 mop->mo_txnid = *kptr;
515 txn->mt_env->me_pghead = mop;
516 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
521 DPRINTF("IDL read txn %lu root %lu num %lu",
522 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
523 for (i=0; i<idl[0]; i++) {
524 DPRINTF("IDL %lu", idl[i+1]);
528 /* drop this IDL from the DB */
529 mpp.mp_parent = NULL;
531 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
532 leaf = NODEPTR(mpp.mp_page, 0);
533 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
536 if (txn->mt_env->me_pghead) {
538 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
539 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
542 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
544 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
545 MDB_oldpages *mop = txn->mt_env->me_pghead;
546 txn->mt_oldest = oldest;
548 /* FIXME: For now, always use fresh pages. We
549 * really ought to search the free list for a
554 /* peel pages off tail, so we only have to truncate the list */
555 pgno = MDB_IDL_LAST(mop->mo_pages);
556 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
558 if (mop->mo_pages[2] > mop->mo_pages[1])
559 mop->mo_pages[0] = 0;
563 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
564 txn->mt_env->me_pghead = mop->mo_next;
572 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
575 dp->h.md_parent = parent;
576 dp->h.md_pi = parent_idx;
577 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
578 if (pgno == P_INVALID) {
579 dp->p.mp_pgno = txn->mt_next_pgno;
580 txn->mt_next_pgno += num;
582 dp->p.mp_pgno = pgno;
588 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
591 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
593 MDB_page *mp = pp->mp_page;
598 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
600 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
602 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
603 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
604 pgno = dp->p.mp_pgno;
605 memcpy(&dp->p, mp, txn->mt_env->me_psize);
608 mp->mp_flags |= P_DIRTY;
610 /* Update the page number to new touched page. */
611 if (pp->mp_parent != NULL)
612 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
619 mdb_env_sync(MDB_env *env, int force)
622 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
623 if (fdatasync(env->me_fd))
630 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
635 if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
636 DPRINTF("calloc: %s", strerror(errno));
641 txn->mt_flags |= MDB_TXN_RDONLY;
643 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
644 if (txn->mt_u.dirty_queue == NULL) {
648 STAILQ_INIT(txn->mt_u.dirty_queue);
650 pthread_mutex_lock(&env->me_txns->mti_wmutex);
651 env->me_txns->mti_txnid++;
652 txn->mt_free_pgs = env->me_free_pgs;
653 txn->mt_free_pgs[0] = 0;
656 txn->mt_txnid = env->me_txns->mti_txnid;
658 MDB_reader *r = pthread_getspecific(env->me_txkey);
661 pthread_mutex_lock(&env->me_txns->mti_mutex);
662 for (i=0; i<env->me_txns->mti_numreaders; i++)
663 if (env->me_txns->mti_readers[i].mr_pid == 0)
665 if (i == env->me_maxreaders) {
666 pthread_mutex_unlock(&env->me_txns->mti_mutex);
669 env->me_txns->mti_readers[i].mr_pid = getpid();
670 env->me_txns->mti_readers[i].mr_tid = pthread_self();
671 r = &env->me_txns->mti_readers[i];
672 pthread_setspecific(env->me_txkey, r);
673 if (i >= env->me_txns->mti_numreaders)
674 env->me_txns->mti_numreaders = i+1;
675 pthread_mutex_unlock(&env->me_txns->mti_mutex);
677 r->mr_txnid = txn->mt_txnid;
678 txn->mt_u.reader = r;
685 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
690 /* Copy the DB arrays */
691 txn->mt_numdbs = env->me_numdbs;
692 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
693 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
694 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
695 if (txn->mt_numdbs > 2)
696 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
697 (txn->mt_numdbs - 2) * sizeof(MDB_db));
701 txn->mt_flags |= MDB_TXN_METOGGLE;
702 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
705 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
706 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
713 mdb_txn_abort(MDB_txn *txn)
722 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
723 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
727 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
728 txn->mt_u.reader->mr_txnid = 0;
733 /* Discard all dirty pages. */
734 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
735 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
736 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
739 free(txn->mt_u.dirty_queue);
741 while ((mop = txn->mt_env->me_pghead)) {
742 txn->mt_env->me_pghead = mop->mo_next;
747 env->me_txns->mti_txnid--;
748 for (i=2; i<env->me_numdbs; i++)
749 env->me_dbxs[i].md_dirty = 0;
750 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
757 mdb_txn_commit(MDB_txn *txn)
766 struct iovec iov[MDB_COMMIT_PAGES];
769 assert(txn->mt_env != NULL);
773 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
774 DPRINTF("attempt to commit read-only transaction");
779 if (txn != env->me_txn) {
780 DPRINTF("attempt to commit unknown transaction");
785 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
786 DPRINTF("error flag is set, can't commit");
791 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
794 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
795 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
797 /* should only be one record now */
798 if (env->me_pghead) {
802 mop = env->me_pghead;
803 key.mv_size = sizeof(pgno_t);
804 key.mv_data = (char *)&mop->mo_txnid;
805 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
806 data.mv_data = mop->mo_pages;
807 mdb_put0(txn, FREE_DBI, &key, &data, 0);
808 free(env->me_pghead);
809 env->me_pghead = NULL;
811 /* save to free list */
812 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
816 /* make sure last page of freeDB is touched and on freelist */
817 key.mv_size = MAXKEYSIZE+1;
819 mpp.mp_parent = NULL;
821 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
826 ULONG *idl = txn->mt_free_pgs;
827 DPRINTF("IDL write txn %lu root %lu num %lu",
828 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
829 for (i=0; i<idl[0]; i++) {
830 DPRINTF("IDL %lu", idl[i+1]);
834 /* write to last page of freeDB */
835 key.mv_size = sizeof(pgno_t);
836 key.mv_data = (char *)&txn->mt_txnid;
837 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
838 data.mv_data = txn->mt_free_pgs;
839 mdb_put0(txn, FREE_DBI, &key, &data, 0);
842 /* Update DB root pointers. Their pages have already been
843 * touched so this is all in-place and cannot fail.
847 data.mv_size = sizeof(MDB_db);
849 for (i = 2; i < txn->mt_numdbs; i++) {
850 if (txn->mt_dbxs[i].md_dirty) {
851 data.mv_data = &txn->mt_dbs[i];
852 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
857 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
864 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
865 if (dp->p.mp_pgno != next) {
867 DPRINTF("committing %u dirty pages", n);
868 rc = writev(env->me_fd, iov, n);
872 DPRINTF("short write, filesystem full?");
874 DPRINTF("writev: %s", strerror(errno));
881 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
882 next = dp->p.mp_pgno;
884 DPRINTF("committing page %lu", dp->p.mp_pgno);
885 iov[n].iov_len = env->me_psize * dp->h.md_num;
886 iov[n].iov_base = &dp->p;
887 size += iov[n].iov_len;
888 next = dp->p.mp_pgno + dp->h.md_num;
889 /* clear dirty flag */
890 dp->p.mp_flags &= ~P_DIRTY;
891 if (++n >= MDB_COMMIT_PAGES) {
900 DPRINTF("committing %u dirty pages", n);
901 rc = writev(env->me_fd, iov, n);
905 DPRINTF("short write, filesystem full?");
907 DPRINTF("writev: %s", strerror(errno));
914 /* Drop the dirty pages.
916 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
917 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
918 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
922 if ((n = mdb_env_sync(env, 0)) != 0 ||
923 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
929 /* update the DB tables */
931 int toggle = !env->me_db_toggle;
933 for (i = 2; i < env->me_numdbs; i++) {
934 if (txn->mt_dbxs[i].md_dirty) {
935 env->me_dbs[toggle][i] = txn->mt_dbs[i];
936 txn->mt_dbxs[i].md_dirty = 0;
939 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
940 txn->mt_dbxs[i].md_dirty = 0;
941 env->me_dbxs[i] = txn->mt_dbxs[i];
942 env->me_dbs[toggle][i] = txn->mt_dbs[i];
944 env->me_db_toggle = toggle;
945 env->me_numdbs = txn->mt_numdbs;
950 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
951 free(txn->mt_u.dirty_queue);
962 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
971 /* We don't know the page size yet, so use a minimum value.
974 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
976 } else if (rc != PAGESIZE) {
979 DPRINTF("read: %s", strerror(errno));
983 p = (MDB_page *)page;
985 if (!F_ISSET(p->mp_flags, P_META)) {
986 DPRINTF("page %lu not a meta page", p->mp_pgno);
991 if (m->mm_magic != MDB_MAGIC) {
992 DPRINTF("meta has invalid magic");
996 if (m->mm_version != MDB_VERSION) {
997 DPRINTF("database is version %u, expected version %u",
998 m->mm_version, MDB_VERSION);
999 return MDB_VERSION_MISMATCH;
1002 memcpy(meta, m, sizeof(*m));
1007 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1014 DPRINTF("writing new meta page");
1015 psize = sysconf(_SC_PAGE_SIZE);
1017 meta->mm_magic = MDB_MAGIC;
1018 meta->mm_version = MDB_VERSION;
1019 meta->mm_psize = psize;
1020 meta->mm_last_pg = 1;
1021 meta->mm_flags = env->me_flags & 0xffff;
1022 meta->mm_flags |= MDB_INTEGERKEY;
1023 meta->mm_dbs[0].md_root = P_INVALID;
1024 meta->mm_dbs[1].md_root = P_INVALID;
1026 p = calloc(2, psize);
1028 p->mp_flags = P_META;
1031 memcpy(m, meta, sizeof(*meta));
1033 q = (MDB_page *)((char *)p + psize);
1036 q->mp_flags = P_META;
1039 memcpy(m, meta, sizeof(*meta));
1041 rc = write(env->me_fd, p, psize * 2);
1043 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1047 mdb_env_write_meta(MDB_txn *txn)
1055 assert(txn != NULL);
1056 assert(txn->mt_env != NULL);
1058 DPRINTF("writing meta page %d for root page %lu",
1059 !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE), txn->mt_dbs[MAIN_DBI].md_root);
1063 ptr = (char *)&meta;
1064 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1065 len = sizeof(MDB_meta) - off;
1068 meta.mm_dbs[0] = txn->mt_dbs[0];
1069 meta.mm_dbs[1] = txn->mt_dbs[1];
1070 meta.mm_last_pg = txn->mt_next_pgno - 1;
1071 meta.mm_txnid = txn->mt_txnid;
1073 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1074 off += env->me_psize;
1077 rc = pwrite(env->me_fd, ptr, len, off);
1079 DPRINTF("write failed, disk error?");
1087 mdb_env_read_meta(MDB_env *env, int *which)
1091 assert(env != NULL);
1093 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1096 if (env->me_meta != env->me_metas[toggle])
1097 env->me_meta = env->me_metas[toggle];
1101 DPRINTF("Using meta page %d", toggle);
1107 mdb_env_create(MDB_env **env)
1111 e = calloc(1, sizeof(MDB_env));
1112 if (!e) return ENOMEM;
1114 e->me_maxreaders = DEFAULT_READERS;
1124 mdb_env_set_mapsize(MDB_env *env, size_t size)
1128 env->me_mapsize = size;
1133 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1135 env->me_maxdbs = dbs;
1140 mdb_env_set_maxreaders(MDB_env *env, int readers)
1142 env->me_maxreaders = readers;
1147 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1149 if (!env || !readers)
1151 *readers = env->me_maxreaders;
1156 mdb_env_open2(MDB_env *env, unsigned int flags)
1162 env->me_flags = flags;
1164 memset(&meta, 0, sizeof(meta));
1166 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1169 DPRINTF("new mdbenv");
1173 if (!env->me_mapsize) {
1174 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1178 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1180 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1182 if (env->me_map == MAP_FAILED)
1186 meta.mm_mapsize = env->me_mapsize;
1187 if (flags & MDB_FIXEDMAP)
1188 meta.mm_address = env->me_map;
1189 i = mdb_env_init_meta(env, &meta);
1190 if (i != MDB_SUCCESS) {
1191 munmap(env->me_map, env->me_mapsize);
1195 env->me_psize = meta.mm_psize;
1197 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1198 env->me_metas[0] = METADATA(p);
1199 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1201 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1204 DPRINTF("opened database version %u, pagesize %u",
1205 env->me_meta->mm_version, env->me_psize);
1206 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1207 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1208 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1209 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1210 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1211 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1217 mdb_env_reader_dest(void *ptr)
1219 MDB_reader *reader = ptr;
1221 reader->mr_txnid = 0;
1226 /* downgrade the exclusive lock on the region back to shared */
1228 mdb_env_share_locks(MDB_env *env)
1230 struct flock lock_info;
1232 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1234 memset((void *)&lock_info, 0, sizeof(lock_info));
1235 lock_info.l_type = F_RDLCK;
1236 lock_info.l_whence = SEEK_SET;
1237 lock_info.l_start = 0;
1238 lock_info.l_len = 1;
1239 fcntl(env->me_lfd, F_SETLK, &lock_info);
1243 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1247 struct flock lock_info;
1251 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1255 /* Try to get exclusive lock. If we succeed, then
1256 * nobody is using the lock region and we should initialize it.
1258 memset((void *)&lock_info, 0, sizeof(lock_info));
1259 lock_info.l_type = F_WRLCK;
1260 lock_info.l_whence = SEEK_SET;
1261 lock_info.l_start = 0;
1262 lock_info.l_len = 1;
1263 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1267 lock_info.l_type = F_RDLCK;
1268 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1274 size = lseek(env->me_lfd, 0, SEEK_END);
1275 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1276 if (size < rsize && *excl) {
1277 if (ftruncate(env->me_lfd, rsize) != 0) {
1283 size = rsize - sizeof(MDB_txninfo);
1284 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1286 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1288 if (env->me_txns == MAP_FAILED) {
1293 pthread_mutexattr_t mattr;
1295 pthread_mutexattr_init(&mattr);
1296 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1300 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1301 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1302 env->me_txns->mti_version = MDB_VERSION;
1303 env->me_txns->mti_magic = MDB_MAGIC;
1304 env->me_txns->mti_txnid = 0;
1305 env->me_txns->mti_numreaders = 0;
1308 if (env->me_txns->mti_magic != MDB_MAGIC) {
1309 DPRINTF("lock region has invalid magic");
1313 if (env->me_txns->mti_version != MDB_VERSION) {
1314 DPRINTF("lock region is version %u, expected version %u",
1315 env->me_txns->mti_version, MDB_VERSION);
1316 rc = MDB_VERSION_MISMATCH;
1319 if (errno != EACCES && errno != EAGAIN) {
1333 #define LOCKNAME "/lock.mdb"
1334 #define DATANAME "/data.mdb"
1336 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1338 int oflags, rc, len, excl;
1339 char *lpath, *dpath;
1342 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1345 dpath = lpath + len + sizeof(LOCKNAME);
1346 sprintf(lpath, "%s" LOCKNAME, path);
1347 sprintf(dpath, "%s" DATANAME, path);
1349 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1353 if (F_ISSET(flags, MDB_RDONLY))
1356 oflags = O_RDWR | O_CREAT;
1358 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1363 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1364 /* synchronous fd for meta writes */
1365 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1367 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1372 env->me_path = strdup(path);
1373 DPRINTF("opened dbenv %p", (void *) env);
1374 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1376 mdb_env_share_locks(env);
1377 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1378 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1379 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1385 if (env->me_fd >= 0) {
1389 if (env->me_lfd >= 0) {
1399 mdb_env_close(MDB_env *env)
1404 free(env->me_dbs[1]);
1405 free(env->me_dbs[0]);
1409 pthread_key_delete(env->me_txkey);
1412 munmap(env->me_map, env->me_mapsize);
1417 pid_t pid = getpid();
1418 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1420 for (i=0; i<env->me_txns->mti_numreaders; i++)
1421 if (env->me_txns->mti_readers[i].mr_pid == pid)
1422 env->me_txns->mti_readers[i].mr_pid = 0;
1423 munmap(env->me_txns, size);
1429 /* Search for key within a leaf page, using binary search.
1430 * Returns the smallest entry larger or equal to the key.
1431 * If exactp is non-null, stores whether the found entry was an exact match
1432 * in *exactp (1 or 0).
1433 * If kip is non-null, stores the index of the found entry in *kip.
1434 * If no entry larger or equal to the key is found, returns NULL.
1437 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1438 int *exactp, unsigned int *kip)
1446 DPRINTF("searching %u keys in %s page %lu",
1448 IS_LEAF(mp) ? "leaf" : "branch",
1451 assert(NUMKEYS(mp) > 0);
1453 memset(&nodekey, 0, sizeof(nodekey));
1455 low = IS_LEAF(mp) ? 0 : 1;
1456 high = NUMKEYS(mp) - 1;
1457 while (low <= high) {
1458 i = (low + high) >> 1;
1459 node = NODEPTR(mp, i);
1461 nodekey.mv_size = node->mn_ksize;
1462 nodekey.mv_data = NODEKEY(node);
1464 if (txn->mt_dbxs[dbi].md_cmp)
1465 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1467 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1470 DPRINTF("found leaf index %u [%.*s], rc = %i",
1471 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1473 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1474 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1485 if (rc > 0) { /* Found entry is less than the key. */
1486 i++; /* Skip to get the smallest entry larger than key. */
1487 if (i >= NUMKEYS(mp))
1488 /* There is no entry larger or equal to the key. */
1492 *exactp = (rc == 0);
1493 if (kip) /* Store the key index if requested. */
1496 return NODEPTR(mp, i);
1500 cursor_pop_page(MDB_cursor *cursor)
1504 top = CURSOR_TOP(cursor);
1507 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1513 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1517 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1519 if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1521 ppage->mp_page = mp;
1522 CURSOR_PUSH(cursor, ppage);
1527 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1532 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1534 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1535 if (dp->p.mp_pgno == pgno) {
1543 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1545 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1551 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1552 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1554 MDB_page *mp = mpp->mp_page;
1557 if (cursor && cursor_push_page(cursor, mp) == NULL)
1560 while (IS_BRANCH(mp)) {
1564 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1565 assert(NUMKEYS(mp) > 1);
1566 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1568 if (key == NULL) /* Initialize cursor to first page. */
1570 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1571 /* cursor to last page */
1575 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1577 i = NUMKEYS(mp) - 1;
1585 DPRINTF("following index %u for key %.*s",
1586 i, (int)key->mv_size, (char *)key->mv_data);
1587 assert(i < NUMKEYS(mp));
1588 node = NODEPTR(mp, i);
1591 CURSOR_TOP(cursor)->mp_ki = i;
1593 mpp->mp_parent = mp;
1594 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1599 if (cursor && cursor_push_page(cursor, mp) == NULL)
1603 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1604 if ((rc = mdb_touch(txn, mpp)) != 0)
1606 dh = ((MDB_dhead *)mpp->mp_page)-1;
1607 dh->md_parent = mpp->mp_parent;
1608 dh->md_pi = mpp->mp_pi;
1615 DPRINTF("internal error, index points to a %02X page!?",
1620 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1621 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1626 /* Search for the page a given key should be in.
1627 * Stores a pointer to the found page in *mpp.
1628 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1629 * If cursor is non-null, pushes parent pages on the cursor stack.
1630 * If modify is true, visited pages are updated with new page numbers.
1633 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1634 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1639 /* Choose which root page to start with. If a transaction is given
1640 * use the root page from the transaction, otherwise read the last
1641 * committed root page.
1643 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1644 DPRINTF("transaction has failed, must abort");
1647 root = txn->mt_dbs[dbi].md_root;
1649 if (root == P_INVALID) { /* Tree is empty. */
1650 DPRINTF("tree is empty");
1651 return MDB_NOTFOUND;
1654 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1657 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1660 /* For sub-databases, update main root first */
1661 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1663 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1667 txn->mt_dbxs[dbi].md_dirty = 1;
1669 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1670 mpp->mp_parent = NULL;
1672 if ((rc = mdb_touch(txn, mpp)))
1674 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1678 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1682 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1684 MDB_page *omp; /* overflow mpage */
1687 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1688 data->mv_size = leaf->mn_dsize;
1689 data->mv_data = NODEDATA(leaf);
1693 /* Read overflow data.
1695 data->mv_size = leaf->mn_dsize;
1696 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1697 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1698 DPRINTF("read overflow page %lu failed", pgno);
1701 data->mv_data = omp;
1707 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1708 MDB_val *key, MDB_val *data)
1716 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1718 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1721 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1725 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1728 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1729 if (leaf && exact) {
1730 /* Return first duplicate data item */
1731 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1734 mdb_xcursor_init0(txn, dbi, &mx);
1735 mdb_xcursor_init1(txn, dbi, &mx, leaf);
1736 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1737 if (rc != MDB_SUCCESS)
1739 leaf = NODEPTR(mpp.mp_page, 0);
1741 rc = mdb_read_data(txn, leaf, data);
1750 mdb_sibling(MDB_cursor *cursor, int move_right)
1754 MDB_ppage *parent, *top;
1757 top = CURSOR_TOP(cursor);
1758 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1759 return MDB_NOTFOUND; /* root has no siblings */
1762 DPRINTF("parent page is page %lu, index %u",
1763 parent->mp_page->mp_pgno, parent->mp_ki);
1765 cursor_pop_page(cursor);
1766 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1767 : (parent->mp_ki == 0)) {
1768 DPRINTF("no more keys left, moving to %s sibling",
1769 move_right ? "right" : "left");
1770 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1772 parent = CURSOR_TOP(cursor);
1778 DPRINTF("just moving to %s index key %u",
1779 move_right ? "right" : "left", parent->mp_ki);
1781 assert(IS_BRANCH(parent->mp_page));
1783 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1784 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1787 mp->parent = parent->mp_page;
1788 mp->parent_index = parent->mp_ki;
1791 cursor_push_page(cursor, mp);
1797 mdb_set_key(MDB_node *node, MDB_val *key)
1802 key->mv_size = node->mn_ksize;
1803 key->mv_data = NODEKEY(node);
1809 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1816 if (cursor->mc_eof) {
1817 return MDB_NOTFOUND;
1820 assert(cursor->mc_initialized);
1822 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1823 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1824 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1825 if (op != MDB_NEXT || rc == MDB_SUCCESS)
1830 top = CURSOR_TOP(cursor);
1833 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1835 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1836 DPRINTF("=====> move to next sibling page");
1837 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1839 return MDB_NOTFOUND;
1841 top = CURSOR_TOP(cursor);
1843 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1847 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1848 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1850 assert(IS_LEAF(mp));
1851 leaf = NODEPTR(mp, top->mp_ki);
1854 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1857 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1858 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1859 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1860 if (rc != MDB_SUCCESS)
1865 return mdb_set_key(leaf, key);
1869 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1876 assert(cursor->mc_initialized);
1878 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1879 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1880 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1881 if (op != MDB_PREV || rc == MDB_SUCCESS)
1886 top = CURSOR_TOP(cursor);
1889 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1891 if (top->mp_ki == 0) {
1892 DPRINTF("=====> move to prev sibling page");
1893 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1894 return MDB_NOTFOUND;
1896 top = CURSOR_TOP(cursor);
1898 top->mp_ki = NUMKEYS(mp) - 1;
1899 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1905 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1906 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1908 assert(IS_LEAF(mp));
1909 leaf = NODEPTR(mp, top->mp_ki);
1912 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1915 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1916 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1917 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1918 if (rc != MDB_SUCCESS)
1923 return mdb_set_key(leaf, key);
1927 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1928 MDB_cursor_op op, int *exactp)
1937 assert(key->mv_size > 0);
1939 while (CURSOR_TOP(cursor) != NULL)
1940 cursor_pop_page(cursor);
1942 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1943 if (rc != MDB_SUCCESS)
1945 assert(IS_LEAF(mpp.mp_page));
1947 top = CURSOR_TOP(cursor);
1948 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1949 if (exactp != NULL && !*exactp) {
1950 /* MDB_SET specified and not an exact match. */
1951 return MDB_NOTFOUND;
1955 DPRINTF("===> inexact leaf not found, goto sibling");
1956 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1957 return rc; /* no entries matched */
1958 top = CURSOR_TOP(cursor);
1960 mpp.mp_page = top->mp_page;
1961 assert(IS_LEAF(mpp.mp_page));
1962 leaf = NODEPTR(mpp.mp_page, 0);
1965 cursor->mc_initialized = 1;
1969 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1972 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1973 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1974 if (op == MDB_SET || op == MDB_SET_RANGE) {
1975 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1979 if (op == MDB_GET_BOTH) {
1984 op2 = MDB_SET_RANGE;
1986 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
1987 if (rc != MDB_SUCCESS)
1993 rc = mdb_set_key(leaf, key);
1994 if (rc == MDB_SUCCESS) {
1995 DPRINTF("==> cursor placed on key %.*s",
1996 (int)key->mv_size, (char *)key->mv_data);
2004 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2010 while (CURSOR_TOP(cursor) != NULL)
2011 cursor_pop_page(cursor);
2013 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2014 if (rc != MDB_SUCCESS)
2016 assert(IS_LEAF(mpp.mp_page));
2018 leaf = NODEPTR(mpp.mp_page, 0);
2019 cursor->mc_initialized = 1;
2023 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2026 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2027 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2028 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2033 return mdb_set_key(leaf, key);
2037 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2045 while (CURSOR_TOP(cursor) != NULL)
2046 cursor_pop_page(cursor);
2048 lkey.mv_size = MAXKEYSIZE+1;
2049 lkey.mv_data = NULL;
2051 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2052 if (rc != MDB_SUCCESS)
2054 assert(IS_LEAF(mpp.mp_page));
2056 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2057 cursor->mc_initialized = 1;
2060 top = CURSOR_TOP(cursor);
2061 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2064 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2067 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2068 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2069 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2075 return mdb_set_key(leaf, key);
2079 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2089 case MDB_GET_BOTH_RANGE:
2097 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2099 } else if (op != MDB_SET_RANGE)
2100 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2102 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2106 case MDB_NEXT_NODUP:
2107 if (!cursor->mc_initialized)
2108 rc = mdb_cursor_first(cursor, key, data);
2110 rc = mdb_cursor_next(cursor, key, data, op);
2114 case MDB_PREV_NODUP:
2115 if (!cursor->mc_initialized || cursor->mc_eof)
2116 rc = mdb_cursor_last(cursor, key, data);
2118 rc = mdb_cursor_prev(cursor, key, data, op);
2121 rc = mdb_cursor_first(cursor, key, data);
2124 rc = mdb_cursor_last(cursor, key, data);
2127 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2135 /* Allocate a page and initialize it
2138 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2142 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2144 DPRINTF("allocated new mpage %lu, page size %u",
2145 dp->p.mp_pgno, txn->mt_env->me_psize);
2146 dp->p.mp_flags = flags | P_DIRTY;
2147 dp->p.mp_lower = PAGEHDRSZ;
2148 dp->p.mp_upper = txn->mt_env->me_psize;
2150 if (IS_BRANCH(&dp->p))
2151 txn->mt_dbs[dbi].md_branch_pages++;
2152 else if (IS_LEAF(&dp->p))
2153 txn->mt_dbs[dbi].md_leaf_pages++;
2154 else if (IS_OVERFLOW(&dp->p)) {
2155 txn->mt_dbs[dbi].md_overflow_pages += num;
2156 dp->p.mp_pages = num;
2163 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2167 sz = LEAFSIZE(key, data);
2168 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2169 /* put on overflow page */
2170 sz -= data->mv_size - sizeof(pgno_t);
2173 return sz + sizeof(indx_t);
2177 mdb_branch_size(MDB_env *env, MDB_val *key)
2182 if (sz >= env->me_psize / MDB_MINKEYS) {
2183 /* put on overflow page */
2184 /* not implemented */
2185 /* sz -= key->size - sizeof(pgno_t); */
2188 return sz + sizeof(indx_t);
2192 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2193 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2196 size_t node_size = NODESIZE;
2199 MDB_dpage *ofp = NULL; /* overflow page */
2201 assert(mp->mp_upper >= mp->mp_lower);
2203 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2204 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2205 IS_LEAF(mp) ? "leaf" : "branch",
2206 mp->mp_pgno, indx, key ? key->mv_size : 0);
2209 node_size += key->mv_size;
2213 if (F_ISSET(flags, F_BIGDATA)) {
2214 /* Data already on overflow page. */
2215 node_size += sizeof(pgno_t);
2216 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2217 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2218 /* Put data on overflow page. */
2219 DPRINTF("data size is %zu, put on overflow page",
2221 node_size += sizeof(pgno_t);
2222 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2224 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2227 node_size += data->mv_size;
2231 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2232 DPRINTF("not enough room in page %lu, got %u ptrs",
2233 mp->mp_pgno, NUMKEYS(mp));
2234 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2235 mp->mp_upper - mp->mp_lower);
2236 DPRINTF("node size = %zu", node_size);
2240 /* Move higher pointers up one slot. */
2241 for (i = NUMKEYS(mp); i > indx; i--)
2242 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2244 /* Adjust free space offsets. */
2245 ofs = mp->mp_upper - node_size;
2246 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2247 mp->mp_ptrs[indx] = ofs;
2249 mp->mp_lower += sizeof(indx_t);
2251 /* Write the node data. */
2252 node = NODEPTR(mp, indx);
2253 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2254 node->mn_flags = flags;
2256 node->mn_dsize = data->mv_size;
2258 node->mn_pgno = pgno;
2261 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2266 if (F_ISSET(flags, F_BIGDATA))
2267 memcpy(node->mn_data + key->mv_size, data->mv_data,
2270 memcpy(node->mn_data + key->mv_size, data->mv_data,
2273 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2275 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2283 mdb_del_node(MDB_page *mp, indx_t indx)
2286 indx_t i, j, numkeys, ptr;
2290 DPRINTF("delete node %u on %s page %lu", indx,
2291 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2292 assert(indx < NUMKEYS(mp));
2294 node = NODEPTR(mp, indx);
2295 sz = NODESIZE + node->mn_ksize;
2297 if (F_ISSET(node->mn_flags, F_BIGDATA))
2298 sz += sizeof(pgno_t);
2300 sz += NODEDSZ(node);
2303 ptr = mp->mp_ptrs[indx];
2304 numkeys = NUMKEYS(mp);
2305 for (i = j = 0; i < numkeys; i++) {
2307 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2308 if (mp->mp_ptrs[i] < ptr)
2309 mp->mp_ptrs[j] += sz;
2314 base = (char *)mp + mp->mp_upper;
2315 memmove(base + sz, base, ptr - mp->mp_upper);
2317 mp->mp_lower -= sizeof(indx_t);
2322 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2327 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2328 mx->mx_txn.mt_dbs = mx->mx_dbs;
2329 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2330 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2332 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2337 mx->mx_dbxs[dbn+1].md_parent = dbn;
2338 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2339 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2340 mx->mx_dbxs[dbn+1].md_dirty = 0;
2341 mx->mx_txn.mt_numdbs = dbn+2;
2343 SLIST_INIT(&mx->mx_cursor.mc_stack);
2344 mx->mx_cursor.mc_txn = &mx->mx_txn;
2345 mx->mx_cursor.mc_dbi = dbn+1;
2349 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2351 MDB_db *db = NODEDATA(node);
2353 mx->mx_dbs[0] = txn->mt_dbs[0];
2354 mx->mx_dbs[1] = txn->mt_dbs[1];
2356 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2361 mx->mx_dbs[dbn] = *db;
2362 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2363 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2364 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2365 mx->mx_txn.mt_oldest = txn->mt_oldest;
2366 mx->mx_txn.mt_u = txn->mt_u;
2370 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2372 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2373 txn->mt_oldest = mx->mx_txn.mt_oldest;
2374 txn->mt_u = mx->mx_txn.mt_u;
2375 txn->mt_dbs[0] = mx->mx_dbs[0];
2376 txn->mt_dbs[1] = mx->mx_dbs[1];
2377 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2378 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2380 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2381 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2386 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2389 size_t size = sizeof(MDB_cursor);
2391 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2394 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2395 size += sizeof(MDB_xcursor);
2397 if ((cursor = calloc(1, size)) != NULL) {
2398 SLIST_INIT(&cursor->mc_stack);
2399 cursor->mc_dbi = dbi;
2400 cursor->mc_txn = txn;
2401 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2402 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2403 cursor->mc_xcursor = mx;
2404 mdb_xcursor_init0(txn, dbi, mx);
2415 /* Return the count of duplicate data items for the current key */
2417 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2419 if (mc == NULL || countp == NULL)
2422 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2425 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2428 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2433 mdb_cursor_close(MDB_cursor *cursor)
2435 if (cursor != NULL) {
2436 while(!CURSOR_EMPTY(cursor))
2437 cursor_pop_page(cursor);
2438 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2439 mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2440 while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2441 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2449 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2451 indx_t ptr, i, numkeys;
2457 node = NODEPTR(mp, indx);
2458 ptr = mp->mp_ptrs[indx];
2459 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2461 (int)node->mn_ksize, (char *)NODEKEY(node),
2462 (int)key->mv_size, (char *)key->mv_data,
2465 delta = key->mv_size - node->mn_ksize;
2467 if (delta > 0 && SIZELEFT(mp) < delta) {
2468 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2472 numkeys = NUMKEYS(mp);
2473 for (i = 0; i < numkeys; i++) {
2474 if (mp->mp_ptrs[i] <= ptr)
2475 mp->mp_ptrs[i] -= delta;
2478 base = (char *)mp + mp->mp_upper;
2479 len = ptr - mp->mp_upper + NODESIZE;
2480 memmove(base - delta, base, len);
2481 mp->mp_upper -= delta;
2483 node = NODEPTR(mp, indx);
2484 node->mn_ksize = key->mv_size;
2487 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2492 /* Move a node from src to dst.
2495 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2496 MDB_pageparent *dst, indx_t dstindx)
2502 srcnode = NODEPTR(src->mp_page, srcindx);
2503 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2504 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2506 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2507 src->mp_page->mp_pgno,
2508 dstindx, dst->mp_page->mp_pgno);
2510 /* Mark src and dst as dirty. */
2511 if ((rc = mdb_touch(txn, src)) ||
2512 (rc = mdb_touch(txn, dst)))
2515 /* Add the node to the destination page.
2517 key.mv_size = srcnode->mn_ksize;
2518 key.mv_data = NODEKEY(srcnode);
2519 data.mv_size = NODEDSZ(srcnode);
2520 data.mv_data = NODEDATA(srcnode);
2521 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2523 if (rc != MDB_SUCCESS)
2526 /* Delete the node from the source page.
2528 mdb_del_node(src->mp_page, srcindx);
2530 /* Update the parent separators.
2532 if (srcindx == 0 && src->mp_pi != 0) {
2533 DPRINTF("update separator for source page %lu to [%.*s]",
2534 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2535 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2536 &key)) != MDB_SUCCESS)
2540 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2542 nullkey.mv_size = 0;
2543 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2546 if (dstindx == 0 && dst->mp_pi != 0) {
2547 DPRINTF("update separator for destination page %lu to [%.*s]",
2548 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2549 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2550 &key)) != MDB_SUCCESS)
2554 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2556 nullkey.mv_size = 0;
2557 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2564 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2573 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2575 assert(txn != NULL);
2576 assert(src->mp_parent); /* can't merge root page */
2577 assert(dst->mp_parent);
2579 /* Mark src and dst as dirty. */
2580 if ((rc = mdb_touch(txn, src)) ||
2581 (rc = mdb_touch(txn, dst)))
2584 /* Move all nodes from src to dst.
2586 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2587 srcnode = NODEPTR(src->mp_page, i);
2589 key.mv_size = srcnode->mn_ksize;
2590 key.mv_data = NODEKEY(srcnode);
2591 data.mv_size = NODEDSZ(srcnode);
2592 data.mv_data = NODEDATA(srcnode);
2593 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2594 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2595 if (rc != MDB_SUCCESS)
2599 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2600 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2602 /* Unlink the src page from parent.
2604 mdb_del_node(src->mp_parent, src->mp_pi);
2605 if (src->mp_pi == 0) {
2607 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2611 if (IS_LEAF(src->mp_page))
2612 txn->mt_dbs[dbi].md_leaf_pages--;
2614 txn->mt_dbs[dbi].md_branch_pages--;
2616 mpp.mp_page = src->mp_parent;
2617 dh = (MDB_dhead *)src->mp_parent;
2619 mpp.mp_parent = dh->md_parent;
2620 mpp.mp_pi = dh->md_pi;
2622 return mdb_rebalance(txn, dbi, &mpp);
2625 #define FILL_THRESHOLD 250
2628 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2633 indx_t si = 0, di = 0;
2635 assert(txn != NULL);
2636 assert(mpp != NULL);
2638 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2639 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2640 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2642 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2643 DPRINTF("no need to rebalance page %lu, above fill threshold",
2644 mpp->mp_page->mp_pgno);
2648 if (mpp->mp_parent == NULL) {
2649 if (NUMKEYS(mpp->mp_page) == 0) {
2650 DPRINTF("tree is completely empty");
2651 txn->mt_dbs[dbi].md_root = P_INVALID;
2652 txn->mt_dbs[dbi].md_depth--;
2653 txn->mt_dbs[dbi].md_leaf_pages--;
2654 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2655 DPRINTF("collapsing root page!");
2656 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2657 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2659 txn->mt_dbs[dbi].md_depth--;
2660 txn->mt_dbs[dbi].md_branch_pages--;
2662 DPRINTF("root page doesn't need rebalancing");
2666 /* The parent (branch page) must have at least 2 pointers,
2667 * otherwise the tree is invalid.
2669 assert(NUMKEYS(mpp->mp_parent) > 1);
2671 /* Leaf page fill factor is below the threshold.
2672 * Try to move keys from left or right neighbor, or
2673 * merge with a neighbor page.
2678 if (mpp->mp_pi == 0) {
2679 /* We're the leftmost leaf in our parent.
2681 DPRINTF("reading right neighbor");
2682 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2683 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2685 npp.mp_pi = mpp->mp_pi + 1;
2687 di = NUMKEYS(mpp->mp_page);
2689 /* There is at least one neighbor to the left.
2691 DPRINTF("reading left neighbor");
2692 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2693 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2695 npp.mp_pi = mpp->mp_pi - 1;
2696 si = NUMKEYS(npp.mp_page) - 1;
2699 npp.mp_parent = mpp->mp_parent;
2701 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2702 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2704 /* If the neighbor page is above threshold and has at least two
2705 * keys, move one key from it.
2707 * Otherwise we should try to merge them.
2709 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2710 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2711 else { /* FIXME: if (has_enough_room()) */
2712 if (mpp->mp_pi == 0)
2713 return mdb_merge(txn, dbi, &npp, mpp);
2715 return mdb_merge(txn, dbi, mpp, &npp);
2720 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2724 /* add overflow pages to free list */
2725 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2729 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2730 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2731 for (i=0; i<ovpages; i++) {
2732 DPRINTF("freed ov page %lu", pg);
2733 mdb_midl_insert(txn->mt_free_pgs, pg);
2737 mdb_del_node(mpp->mp_page, ki);
2738 txn->mt_dbs[dbi].md_entries--;
2739 rc = mdb_rebalance(txn, dbi, mpp);
2740 if (rc != MDB_SUCCESS)
2741 txn->mt_flags |= MDB_TXN_ERROR;
2747 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2748 MDB_val *key, MDB_val *data,
2756 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2758 assert(key != NULL);
2760 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2763 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2767 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2771 mpp.mp_parent = NULL;
2773 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2776 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2777 if (leaf == NULL || !exact) {
2778 return MDB_NOTFOUND;
2781 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2785 mdb_xcursor_init0(txn, dbi, &mx);
2786 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2787 if (flags == MDB_DEL_DUP) {
2788 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2789 mdb_xcursor_fini(txn, dbi, &mx);
2790 if (rc != MDB_SUCCESS)
2792 /* If sub-DB still has entries, we're done */
2793 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2794 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2798 /* otherwise fall thru and delete the sub-DB */
2800 /* add all the child DB's pages to the free list */
2801 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2802 NULL, &mx.mx_cursor, 0, &mp2);
2803 if (rc == MDB_SUCCESS) {
2804 MDB_ppage *top, *parent;
2808 cursor_pop_page(&mx.mx_cursor);
2809 top = CURSOR_TOP(&mx.mx_cursor);
2811 parent = SLIST_NEXT(top, mp_entry);
2812 while (parent != NULL) {
2813 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2814 ni = NODEPTR(top->mp_page, i);
2815 mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2819 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2820 cursor_pop_page(&mx.mx_cursor);
2821 top = CURSOR_TOP(&mx.mx_cursor);
2822 parent = SLIST_NEXT(top, mp_entry);
2824 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2825 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2830 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2835 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2838 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2841 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2842 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2843 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2844 * refer to a node in the new right sibling page.
2847 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2848 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2851 int rc = MDB_SUCCESS, ins_new = 0;
2854 unsigned int i, j, split_indx;
2856 MDB_val sepkey, rkey, rdata;
2858 MDB_dpage *mdp, *rdp, *pdp;
2861 assert(txn != NULL);
2863 dh = ((MDB_dhead *)*mpp) - 1;
2864 mdp = (MDB_dpage *)dh;
2865 newindx = *newindxp;
2867 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2868 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2869 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2871 if (mdp->h.md_parent == NULL) {
2872 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2875 mdp->h.md_parent = &pdp->p;
2876 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2877 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2878 txn->mt_dbs[dbi].md_depth++;
2880 /* Add left (implicit) pointer. */
2881 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2882 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2885 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2888 /* Create a right sibling. */
2889 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2891 rdp->h.md_parent = mdp->h.md_parent;
2892 rdp->h.md_pi = mdp->h.md_pi + 1;
2893 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2895 /* Move half of the keys to the right sibling. */
2896 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2898 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2899 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2900 mdp->p.mp_lower = PAGEHDRSZ;
2901 mdp->p.mp_upper = txn->mt_env->me_psize;
2903 split_indx = NUMKEYS(copy) / 2 + 1;
2905 /* First find the separating key between the split pages.
2907 memset(&sepkey, 0, sizeof(sepkey));
2908 if (newindx == split_indx) {
2909 sepkey.mv_size = newkey->mv_size;
2910 sepkey.mv_data = newkey->mv_data;
2912 node = NODEPTR(copy, split_indx);
2913 sepkey.mv_size = node->mn_ksize;
2914 sepkey.mv_data = NODEKEY(node);
2917 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2919 /* Copy separator key to the parent.
2921 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2922 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2923 &sepkey, NULL, rdp->p.mp_pgno);
2925 /* Right page might now have changed parent.
2926 * Check if left page also changed parent.
2928 if (rdp->h.md_parent != mdp->h.md_parent &&
2929 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2930 mdp->h.md_parent = rdp->h.md_parent;
2931 mdp->h.md_pi = rdp->h.md_pi - 1;
2934 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2935 &sepkey, NULL, rdp->p.mp_pgno, 0);
2937 if (rc != MDB_SUCCESS) {
2942 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2943 if (i < split_indx) {
2944 /* Re-insert in left sibling. */
2947 /* Insert in right sibling. */
2948 if (i == split_indx)
2949 /* Reset insert index for right sibling. */
2950 j = (i == newindx && ins_new);
2954 if (i == newindx && !ins_new) {
2955 /* Insert the original entry that caused the split. */
2956 rkey.mv_data = newkey->mv_data;
2957 rkey.mv_size = newkey->mv_size;
2958 if (IS_LEAF(&mdp->p)) {
2959 rdata.mv_data = newdata->mv_data;
2960 rdata.mv_size = newdata->mv_size;
2967 /* Update page and index for the new key. */
2970 } else if (i == NUMKEYS(copy)) {
2973 node = NODEPTR(copy, i);
2974 rkey.mv_data = NODEKEY(node);
2975 rkey.mv_size = node->mn_ksize;
2976 if (IS_LEAF(&mdp->p)) {
2977 rdata.mv_data = NODEDATA(node);
2978 rdata.mv_size = node->mn_dsize;
2980 pgno = node->mn_pgno;
2981 flags = node->mn_flags;
2986 if (!IS_LEAF(&mdp->p) && j == 0) {
2987 /* First branch index doesn't need key data. */
2991 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2999 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3000 MDB_val *key, MDB_val *data, unsigned int flags)
3002 int rc = MDB_SUCCESS, exact;
3006 MDB_val xdata, *rdata;
3009 DPRINTF("==> put key %.*s, size %zu, data size %zu",
3010 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
3012 mpp.mp_parent = NULL;
3014 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3015 if (rc == MDB_SUCCESS) {
3016 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3017 if (leaf && exact) {
3018 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3021 if (flags == MDB_NOOVERWRITE) {
3022 DPRINTF("duplicate key %.*s",
3023 (int)key->mv_size, (char *)key->mv_data);
3024 return MDB_KEYEXIST;
3026 /* same size, just replace it */
3027 if (NODEDSZ(leaf) == data->mv_size) {
3028 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3031 mdb_del_node(mpp.mp_page, ki);
3033 if (leaf == NULL) { /* append if not found */
3034 ki = NUMKEYS(mpp.mp_page);
3035 DPRINTF("appending key at index %i", ki);
3037 } else if (rc == MDB_NOTFOUND) {
3039 /* new file, just write a root leaf page */
3040 DPRINTF("allocating new root leaf page");
3041 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3044 mpp.mp_page = &dp->p;
3045 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3046 txn->mt_dbs[dbi].md_depth++;
3052 assert(IS_LEAF(mpp.mp_page));
3053 DPRINTF("there are %u keys, should insert new key at index %i",
3054 NUMKEYS(mpp.mp_page), ki);
3056 /* For sorted dups, the data item at this level is a DB record
3057 * for a child DB; the actual data elements are stored as keys
3060 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3062 xdata.mv_size = sizeof(MDB_db);
3063 xdata.mv_data = &dummy;
3064 memset(&dummy, 0, sizeof(dummy));
3065 dummy.md_root = P_INVALID;
3070 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3071 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3073 /* There is room already in this leaf page. */
3074 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3077 if (rc != MDB_SUCCESS)
3078 txn->mt_flags |= MDB_TXN_ERROR;
3080 txn->mt_dbs[dbi].md_entries++;
3082 /* Remember if we just added a subdatabase */
3083 if (flags & F_SUBDATA) {
3084 leaf = NODEPTR(mpp.mp_page, ki);
3085 leaf->mn_flags |= F_SUBDATA;
3088 /* Now store the actual data in the child DB. Note that we're
3089 * storing the user data in the keys field, so there are strict
3090 * size limits on dupdata. The actual data fields of the child
3091 * DB are all zero size.
3093 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3096 leaf = NODEPTR(mpp.mp_page, ki);
3098 mdb_xcursor_init0(txn, dbi, &mx);
3099 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3102 if (flags == MDB_NODUPDATA)
3103 flags = MDB_NOOVERWRITE;
3104 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3105 mdb_xcursor_fini(txn, dbi, &mx);
3106 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3116 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3117 MDB_val *key, MDB_val *data, unsigned int flags)
3119 assert(key != NULL);
3120 assert(data != NULL);
3122 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3125 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3129 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3133 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3136 return mdb_put0(txn, dbi, key, data, flags);
3140 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3145 *arg = env->me_flags;
3150 mdb_env_get_path(MDB_env *env, const char **arg)
3155 *arg = env->me_path;
3160 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3162 arg->ms_psize = env->me_psize;
3163 arg->ms_depth = db->md_depth;
3164 arg->ms_branch_pages = db->md_branch_pages;
3165 arg->ms_leaf_pages = db->md_leaf_pages;
3166 arg->ms_overflow_pages = db->md_overflow_pages;
3167 arg->ms_entries = db->md_entries;
3172 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3174 if (env == NULL || arg == NULL)
3177 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3180 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3190 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3191 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3195 /* Is the DB already open? */
3197 for (i=2; i<txn->mt_numdbs; i++) {
3198 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3199 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3205 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3208 /* Find the DB info */
3210 key.mv_data = (void *)name;
3211 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3213 /* Create if requested */
3214 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3216 data.mv_size = sizeof(MDB_db);
3217 data.mv_data = &dummy;
3218 memset(&dummy, 0, sizeof(dummy));
3219 dummy.md_root = P_INVALID;
3220 dummy.md_flags = flags & 0xffff;
3221 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3225 /* OK, got info, add to table */
3226 if (rc == MDB_SUCCESS) {
3227 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3228 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3229 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3230 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3231 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3232 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3233 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3234 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3235 *dbi = txn->mt_numdbs;
3242 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3244 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3247 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3250 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3253 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3255 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3256 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3257 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3261 int mdb_set_compare(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_cmp = cmp;
3270 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3272 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3275 txn->mt_dbxs[dbi].md_dcmp = cmp;
3279 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3281 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3284 txn->mt_dbxs[dbi].md_rel = rel;