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;
113 uint32_t mtb_me_toggle;
116 typedef struct MDB_txninfo {
119 #define mti_magic mt1.mtb.mtb_magic
120 #define mti_version mt1.mtb.mtb_version
121 #define mti_mutex mt1.mtb.mtb_mutex
122 #define mti_txnid mt1.mtb.mtb_txnid
123 #define mti_numreaders mt1.mtb.mtb_numreaders
124 #define mti_me_toggle mt1.mtb.mtb_me_toggle
125 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
128 pthread_mutex_t mt2_wmutex;
129 #define mti_wmutex mt2.mt2_wmutex
130 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
132 MDB_reader mti_readers[1];
135 /* Common header for all page types. Overflow pages
136 * occupy a number of contiguous pages with no
137 * headers on any page after the first.
139 typedef struct MDB_page { /* represents a page of storage */
140 #define mp_pgno mp_p.p_pgno
142 pgno_t p_pgno; /* page number */
145 #define P_BRANCH 0x01 /* branch page */
146 #define P_LEAF 0x02 /* leaf page */
147 #define P_OVERFLOW 0x04 /* overflow page */
148 #define P_META 0x08 /* meta page */
149 #define P_DIRTY 0x10 /* dirty page */
150 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
152 #define mp_lower mp_pb.pb.pb_lower
153 #define mp_upper mp_pb.pb.pb_upper
154 #define mp_pages mp_pb.pb_pages
157 indx_t pb_lower; /* lower bound of free space */
158 indx_t pb_upper; /* upper bound of free space */
160 uint32_t pb_pages; /* number of overflow pages */
162 indx_t pb_ksize; /* on a LEAF2 page */
166 indx_t mp_ptrs[1]; /* dynamic size */
169 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
171 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
172 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
173 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
174 ((env)->me_psize - PAGEHDRSZ))
175 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
176 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
177 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
179 #define OVPAGES(size, psize) (PAGEHDRSZ + size + psize - 1) / psize;
181 typedef struct MDB_db {
185 ULONG md_branch_pages;
187 ULONG md_overflow_pages;
195 typedef struct MDB_meta { /* meta (footer) page content */
198 void *mm_address; /* address for fixed mapping */
199 size_t mm_mapsize; /* size of mmap region */
200 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
201 #define mm_psize mm_dbs[0].md_pad
202 #define mm_flags mm_dbs[0].md_flags
203 pgno_t mm_last_pg; /* last used page in file */
204 ULONG mm_txnid; /* txnid that committed this page */
207 typedef struct MDB_dhead { /* a dirty page */
209 unsigned md_pi; /* parent index */
213 typedef struct MDB_dpage {
218 typedef struct MDB_oldpages {
219 struct MDB_oldpages *mo_next;
221 pgno_t mo_pages[1]; /* dynamic */
224 typedef struct MDB_pageparent {
230 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
231 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
233 typedef struct MDB_ppage { /* ordered list of pages */
234 SLIST_ENTRY(MDB_ppage) mp_entry;
236 unsigned int mp_ki; /* cursor index on page */
238 SLIST_HEAD(page_stack, MDB_ppage);
240 /* FIXME: tree depth is mostly bounded, we should just
241 * use a fixed array and avoid malloc/pointer chasing
243 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
244 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
245 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
246 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
252 struct page_stack mc_stack; /* stack of parent pages */
254 short mc_initialized; /* 1 if initialized */
255 short mc_eof; /* 1 if end is reached */
256 struct MDB_xcursor *mc_xcursor;
259 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
261 typedef struct MDB_node {
262 #define mn_pgno mn_p.np_pgno
263 #define mn_dsize mn_p.np_dsize
265 pgno_t np_pgno; /* child page number */
266 uint32_t np_dsize; /* leaf data size */
268 unsigned int mn_flags:4;
269 unsigned int mn_ksize:12; /* key size */
270 #define F_BIGDATA 0x01 /* data put on overflow page */
271 #define F_SUBDATA 0x02 /* data is a sub-database */
275 typedef struct MDB_dbx {
277 MDB_cmp_func *md_cmp; /* user compare function */
278 MDB_cmp_func *md_dcmp; /* user dupsort function */
279 MDB_rel_func *md_rel; /* user relocate function */
281 unsigned int md_dirty;
285 pgno_t mt_next_pgno; /* next unallocated page */
289 pgno_t *mt_free_pgs; /* this is an IDL */
291 MIDL2 *dirty_list; /* modified pages */
294 MDB_dbx *mt_dbxs; /* array */
296 unsigned int mt_numdbs;
298 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
299 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
300 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
301 unsigned int mt_flags;
304 /* Context for sorted-dup records */
305 typedef struct MDB_xcursor {
306 MDB_cursor mx_cursor;
315 int me_mfd; /* just for writing the meta pages */
316 #define MDB_FATAL_ERROR 0x80000000U
318 uint32_t me_extrapad; /* unused for now */
319 unsigned int me_maxreaders;
320 unsigned int me_numdbs;
321 unsigned int me_maxdbs;
324 MDB_txninfo *me_txns;
325 MDB_meta *me_metas[2];
327 MDB_txn *me_txn; /* current write transaction */
329 off_t me_size; /* current file size */
330 pgno_t me_maxpg; /* me_mapsize / me_psize */
331 unsigned int me_psize;
332 unsigned int me_db_toggle;
333 MDB_dbx *me_dbxs; /* array */
335 MDB_oldpages *me_pghead;
336 pthread_key_t me_txkey; /* thread-key for readers */
337 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
338 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
341 #define NODESIZE offsetof(MDB_node, mn_data)
343 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
344 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
345 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
346 #define NODEKEY(node) (void *)((node)->mn_data)
347 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
348 #define NODEPGNO(node) ((node)->mn_pgno)
349 #define NODEDSZ(node) ((node)->mn_dsize)
351 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
353 static int mdb_search_page_root(MDB_txn *txn,
354 MDB_dbi dbi, MDB_val *key,
355 MDB_cursor *cursor, int modify,
356 MDB_pageparent *mpp);
357 static int mdb_search_page(MDB_txn *txn,
358 MDB_dbi dbi, MDB_val *key,
359 MDB_cursor *cursor, int modify,
360 MDB_pageparent *mpp);
362 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
363 static int mdb_env_read_meta(MDB_env *env, int *which);
364 static int mdb_env_write_meta(MDB_txn *txn);
365 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
367 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
368 MDB_val *key, int *exactp, unsigned int *kip);
369 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
370 indx_t indx, MDB_val *key, MDB_val *data,
371 pgno_t pgno, uint8_t flags);
372 static void mdb_del_node(MDB_page *mp, indx_t indx);
373 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
374 MDB_pageparent *mpp, MDB_node *leaf);
375 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
376 MDB_val *key, MDB_val *data, unsigned int flags);
377 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
379 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
380 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
381 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
382 MDB_pageparent *src, indx_t srcindx,
383 MDB_pageparent *dst, indx_t dstindx);
384 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
385 MDB_pageparent *dst);
386 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
387 unsigned int *newindxp, MDB_val *newkey,
388 MDB_val *newdata, pgno_t newpgno);
389 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
391 static void cursor_pop_page(MDB_cursor *cursor);
392 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
395 static int mdb_set_key(MDB_node *node, MDB_val *key);
396 static int mdb_sibling(MDB_cursor *cursor, int move_right);
397 static int mdb_cursor_next(MDB_cursor *cursor,
398 MDB_val *key, MDB_val *data, MDB_cursor_op op);
399 static int mdb_cursor_prev(MDB_cursor *cursor,
400 MDB_val *key, MDB_val *data, MDB_cursor_op op);
401 static int mdb_cursor_set(MDB_cursor *cursor,
402 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
403 static int mdb_cursor_first(MDB_cursor *cursor,
404 MDB_val *key, MDB_val *data);
405 static int mdb_cursor_last(MDB_cursor *cursor,
406 MDB_val *key, MDB_val *data);
408 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
409 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node);
410 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
412 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
414 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
416 static int memncmp(const void *s1, size_t n1,
417 const void *s2, size_t n2);
418 static int memnrcmp(const void *s1, size_t n1,
419 const void *s2, size_t n2);
422 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
424 int diff, len_diff = -1;
427 len_diff = (n1 > n2);
430 diff = memcmp(s1, s2, n1);
431 return diff ? diff : len_diff;
435 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
437 const unsigned char *p1, *p2, *p1_lim;
444 p1 = (const unsigned char *)s1 + n1 - 1;
445 p2 = (const unsigned char *)s2 + n2 - 1;
447 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
449 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
455 mdb_version(int *maj, int *min, int *pat)
457 *maj = MDB_VERSION_MAJOR;
458 *min = MDB_VERSION_MINOR;
459 *pat = MDB_VERSION_PATCH;
460 return MDB_VERSION_STRING;
464 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
466 return txn->mt_dbxs[dbi].md_cmp(a, b);
470 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
472 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
473 #if __BYTE_ORDER == __LITTLE_ENDIAN
477 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
479 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
482 /* Allocate new page(s) for writing */
484 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
487 pgno_t pgno = P_INVALID;
491 if (txn->mt_txnid > 2) {
493 oldest = txn->mt_txnid - 2;
494 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
495 /* See if there's anything in the free DB */
500 mpp.mp_parent = NULL;
502 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
503 leaf = NODEPTR(mpp.mp_page, 0);
504 kptr = (ULONG *)NODEKEY(leaf);
506 /* It's potentially usable, unless there are still
507 * older readers outstanding. Grab it.
509 if (oldest > *kptr) {
514 mdb_read_data(txn, leaf, &data);
515 idl = (ULONG *)data.mv_data;
516 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
517 mop->mo_next = txn->mt_env->me_pghead;
518 mop->mo_txnid = *kptr;
519 txn->mt_env->me_pghead = mop;
520 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
525 DPRINTF("IDL read txn %lu root %lu num %lu",
526 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
527 for (i=0; i<idl[0]; i++) {
528 DPRINTF("IDL %lu", idl[i+1]);
532 /* drop this IDL from the DB */
533 mpp.mp_parent = NULL;
535 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
536 leaf = NODEPTR(mpp.mp_page, 0);
537 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
540 if (txn->mt_env->me_pghead) {
542 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
543 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
546 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
548 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
549 MDB_oldpages *mop = txn->mt_env->me_pghead;
550 txn->mt_oldest = oldest;
552 /* FIXME: For now, always use fresh pages. We
553 * really ought to search the free list for a
558 /* peel pages off tail, so we only have to truncate the list */
559 pgno = MDB_IDL_LAST(mop->mo_pages);
560 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
562 if (mop->mo_pages[2] > mop->mo_pages[1])
563 mop->mo_pages[0] = 0;
567 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
568 txn->mt_env->me_pghead = mop->mo_next;
576 if (pgno == P_INVALID) {
577 /* DB size is maxed out */
578 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
581 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
584 dp->h.md_parent = parent;
585 dp->h.md_pi = parent_idx;
586 if (pgno == P_INVALID) {
587 dp->p.mp_pgno = txn->mt_next_pgno;
588 txn->mt_next_pgno += num;
590 dp->p.mp_pgno = pgno;
592 mid.mid = dp->p.mp_pgno;
594 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
599 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
602 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
604 MDB_page *mp = pp->mp_page;
609 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
611 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
613 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
614 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
615 pgno = dp->p.mp_pgno;
616 memcpy(&dp->p, mp, txn->mt_env->me_psize);
619 mp->mp_flags |= P_DIRTY;
621 /* Update the page number to new touched page. */
622 if (pp->mp_parent != NULL)
623 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
630 mdb_env_sync(MDB_env *env, int force)
633 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
634 if (fdatasync(env->me_fd))
641 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
646 if (env->me_flags & MDB_FATAL_ERROR) {
647 DPRINTF("mdb_txn_begin: environment had fatal error, must shutdown!");
650 if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
651 DPRINTF("calloc: %s", strerror(errno));
656 txn->mt_flags |= MDB_TXN_RDONLY;
658 txn->mt_u.dirty_list = env->me_dirty_list;
659 txn->mt_u.dirty_list[0].mid = 0;
660 txn->mt_free_pgs = env->me_free_pgs;
661 txn->mt_free_pgs[0] = 0;
663 pthread_mutex_lock(&env->me_txns->mti_wmutex);
664 env->me_txns->mti_txnid++;
667 txn->mt_txnid = env->me_txns->mti_txnid;
669 MDB_reader *r = pthread_getspecific(env->me_txkey);
672 pthread_mutex_lock(&env->me_txns->mti_mutex);
673 for (i=0; i<env->me_txns->mti_numreaders; i++)
674 if (env->me_txns->mti_readers[i].mr_pid == 0)
676 if (i == env->me_maxreaders) {
677 pthread_mutex_unlock(&env->me_txns->mti_mutex);
680 env->me_txns->mti_readers[i].mr_pid = getpid();
681 env->me_txns->mti_readers[i].mr_tid = pthread_self();
682 r = &env->me_txns->mti_readers[i];
683 pthread_setspecific(env->me_txkey, r);
684 if (i >= env->me_txns->mti_numreaders)
685 env->me_txns->mti_numreaders = i+1;
686 pthread_mutex_unlock(&env->me_txns->mti_mutex);
688 r->mr_txnid = txn->mt_txnid;
689 txn->mt_u.reader = r;
696 toggle = env->me_txns->mti_me_toggle;
697 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
702 /* Copy the DB arrays */
703 txn->mt_numdbs = env->me_numdbs;
704 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
705 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
706 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
707 if (txn->mt_numdbs > 2)
708 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
709 (txn->mt_numdbs - 2) * sizeof(MDB_db));
713 txn->mt_flags |= MDB_TXN_METOGGLE;
714 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
717 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
718 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
725 mdb_txn_abort(MDB_txn *txn)
733 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
734 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
738 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
739 txn->mt_u.reader->mr_txnid = 0;
744 /* Discard all dirty pages. */
745 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
746 free(txn->mt_u.dirty_list[i].mptr);
748 while ((mop = txn->mt_env->me_pghead)) {
749 txn->mt_env->me_pghead = mop->mo_next;
754 env->me_txns->mti_txnid--;
755 for (i=2; i<env->me_numdbs; i++)
756 env->me_dbxs[i].md_dirty = 0;
757 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
764 mdb_txn_commit(MDB_txn *txn)
773 struct iovec iov[MDB_COMMIT_PAGES];
776 assert(txn->mt_env != NULL);
780 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
781 DPRINTF("attempt to commit read-only transaction");
786 if (txn != env->me_txn) {
787 DPRINTF("attempt to commit unknown transaction");
792 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
793 DPRINTF("error flag is set, can't commit");
798 if (!txn->mt_u.dirty_list[0].mid)
801 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
802 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
804 /* should only be one record now */
805 if (env->me_pghead) {
809 mop = env->me_pghead;
810 key.mv_size = sizeof(pgno_t);
811 key.mv_data = (char *)&mop->mo_txnid;
812 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
813 data.mv_data = mop->mo_pages;
814 mdb_put0(txn, FREE_DBI, &key, &data, 0);
815 free(env->me_pghead);
816 env->me_pghead = NULL;
818 /* save to free list */
819 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
823 /* make sure last page of freeDB is touched and on freelist */
824 key.mv_size = MAXKEYSIZE+1;
826 mpp.mp_parent = NULL;
828 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
833 ULONG *idl = txn->mt_free_pgs;
834 DPRINTF("IDL write txn %lu root %lu num %lu",
835 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
836 for (i=0; i<idl[0]; i++) {
837 DPRINTF("IDL %lu", idl[i+1]);
841 /* write to last page of freeDB */
842 key.mv_size = sizeof(pgno_t);
843 key.mv_data = (char *)&txn->mt_txnid;
844 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
845 data.mv_data = txn->mt_free_pgs;
846 mdb_put0(txn, FREE_DBI, &key, &data, 0);
849 /* Update DB root pointers. Their pages have already been
850 * touched so this is all in-place and cannot fail.
854 data.mv_size = sizeof(MDB_db);
856 for (i = 2; i < txn->mt_numdbs; i++) {
857 if (txn->mt_dbxs[i].md_dirty) {
858 data.mv_data = &txn->mt_dbs[i];
859 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
864 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
871 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
872 dp = txn->mt_u.dirty_list[i].mptr;
873 if (dp->p.mp_pgno != next) {
875 DPRINTF("committing %u dirty pages", n);
876 rc = writev(env->me_fd, iov, n);
880 DPRINTF("short write, filesystem full?");
882 DPRINTF("writev: %s", strerror(errno));
889 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
890 next = dp->p.mp_pgno;
892 DPRINTF("committing page %lu", dp->p.mp_pgno);
893 iov[n].iov_len = env->me_psize * dp->h.md_num;
894 iov[n].iov_base = &dp->p;
895 size += iov[n].iov_len;
896 next = dp->p.mp_pgno + dp->h.md_num;
897 /* clear dirty flag */
898 dp->p.mp_flags &= ~P_DIRTY;
899 if (++n >= MDB_COMMIT_PAGES) {
908 DPRINTF("committing %u dirty pages", n);
909 rc = writev(env->me_fd, iov, n);
913 DPRINTF("short write, filesystem full?");
915 DPRINTF("writev: %s", strerror(errno));
922 /* Drop the dirty pages.
924 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
925 free(txn->mt_u.dirty_list[i].mptr);
927 if ((n = mdb_env_sync(env, 0)) != 0 ||
928 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
934 /* update the DB tables */
936 int toggle = !env->me_db_toggle;
938 for (i = 2; i < env->me_numdbs; i++) {
939 if (txn->mt_dbxs[i].md_dirty) {
940 env->me_dbs[toggle][i] = txn->mt_dbs[i];
941 txn->mt_dbxs[i].md_dirty = 0;
944 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
945 txn->mt_dbxs[i].md_dirty = 0;
946 env->me_dbxs[i] = txn->mt_dbxs[i];
947 env->me_dbs[toggle][i] = txn->mt_dbs[i];
949 env->me_db_toggle = toggle;
950 env->me_numdbs = txn->mt_numdbs;
955 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
966 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
975 /* We don't know the page size yet, so use a minimum value.
978 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
980 } else if (rc != PAGESIZE) {
983 DPRINTF("read: %s", strerror(errno));
987 p = (MDB_page *)page;
989 if (!F_ISSET(p->mp_flags, P_META)) {
990 DPRINTF("page %lu not a meta page", p->mp_pgno);
995 if (m->mm_magic != MDB_MAGIC) {
996 DPRINTF("meta has invalid magic");
1000 if (m->mm_version != MDB_VERSION) {
1001 DPRINTF("database is version %u, expected version %u",
1002 m->mm_version, MDB_VERSION);
1003 return MDB_VERSION_MISMATCH;
1006 memcpy(meta, m, sizeof(*m));
1011 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1018 DPRINTF("writing new meta page");
1019 psize = sysconf(_SC_PAGE_SIZE);
1021 meta->mm_magic = MDB_MAGIC;
1022 meta->mm_version = MDB_VERSION;
1023 meta->mm_psize = psize;
1024 meta->mm_last_pg = 1;
1025 meta->mm_flags = env->me_flags & 0xffff;
1026 meta->mm_flags |= MDB_INTEGERKEY;
1027 meta->mm_dbs[0].md_root = P_INVALID;
1028 meta->mm_dbs[1].md_root = P_INVALID;
1030 p = calloc(2, psize);
1032 p->mp_flags = P_META;
1035 memcpy(m, meta, sizeof(*meta));
1037 q = (MDB_page *)((char *)p + psize);
1040 q->mp_flags = P_META;
1043 memcpy(m, meta, sizeof(*meta));
1045 rc = write(env->me_fd, p, psize * 2);
1047 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1051 mdb_env_write_meta(MDB_txn *txn)
1054 MDB_meta meta, metab;
1056 int rc, len, toggle;
1059 assert(txn != NULL);
1060 assert(txn->mt_env != NULL);
1062 toggle = !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE);
1063 DPRINTF("writing meta page %d for root page %lu",
1064 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1068 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1069 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1071 ptr = (char *)&meta;
1072 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1073 len = sizeof(MDB_meta) - off;
1076 meta.mm_dbs[0] = txn->mt_dbs[0];
1077 meta.mm_dbs[1] = txn->mt_dbs[1];
1078 meta.mm_last_pg = txn->mt_next_pgno - 1;
1079 meta.mm_txnid = txn->mt_txnid;
1082 off += env->me_psize;
1085 /* Write to the SYNC fd */
1086 rc = pwrite(env->me_mfd, ptr, len, off);
1088 DPRINTF("write failed, disk error?");
1089 /* On a failure, the pagecache still contains the new data.
1090 * Write some old data back, to prevent it from being used.
1091 * Use the non-SYNC fd; we know it will fail anyway.
1093 meta.mm_last_pg = metab.mm_last_pg;
1094 meta.mm_txnid = metab.mm_txnid;
1095 rc = pwrite(env->me_fd, ptr, len, off);
1096 env->me_flags |= MDB_FATAL_ERROR;
1099 txn->mt_env->me_txns->mti_me_toggle = toggle;
1105 mdb_env_read_meta(MDB_env *env, int *which)
1109 assert(env != NULL);
1113 else if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1116 if (env->me_meta != env->me_metas[toggle])
1117 env->me_meta = env->me_metas[toggle];
1119 DPRINTF("Using meta page %d", toggle);
1125 mdb_env_create(MDB_env **env)
1129 e = calloc(1, sizeof(MDB_env));
1130 if (!e) return ENOMEM;
1132 e->me_maxreaders = DEFAULT_READERS;
1142 mdb_env_set_mapsize(MDB_env *env, size_t size)
1146 env->me_mapsize = size;
1151 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1153 env->me_maxdbs = dbs;
1158 mdb_env_set_maxreaders(MDB_env *env, int readers)
1160 env->me_maxreaders = readers;
1165 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1167 if (!env || !readers)
1169 *readers = env->me_maxreaders;
1174 mdb_env_open2(MDB_env *env, unsigned int flags)
1180 env->me_flags = flags;
1182 memset(&meta, 0, sizeof(meta));
1184 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1187 DPRINTF("new mdbenv");
1191 if (!env->me_mapsize) {
1192 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1196 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1198 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1200 if (env->me_map == MAP_FAILED)
1204 meta.mm_mapsize = env->me_mapsize;
1205 if (flags & MDB_FIXEDMAP)
1206 meta.mm_address = env->me_map;
1207 i = mdb_env_init_meta(env, &meta);
1208 if (i != MDB_SUCCESS) {
1209 munmap(env->me_map, env->me_mapsize);
1213 env->me_psize = meta.mm_psize;
1215 env->me_maxpg = env->me_mapsize / env->me_psize;
1217 p = (MDB_page *)env->me_map;
1218 env->me_metas[0] = METADATA(p);
1219 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1221 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1224 DPRINTF("opened database version %u, pagesize %u",
1225 env->me_meta->mm_version, env->me_psize);
1226 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1227 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1228 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1229 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1230 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1231 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1237 mdb_env_reader_dest(void *ptr)
1239 MDB_reader *reader = ptr;
1241 reader->mr_txnid = 0;
1246 /* downgrade the exclusive lock on the region back to shared */
1248 mdb_env_share_locks(MDB_env *env)
1250 struct flock lock_info;
1252 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1253 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1254 env->me_txns->mti_me_toggle = 1;
1256 memset((void *)&lock_info, 0, sizeof(lock_info));
1257 lock_info.l_type = F_RDLCK;
1258 lock_info.l_whence = SEEK_SET;
1259 lock_info.l_start = 0;
1260 lock_info.l_len = 1;
1261 fcntl(env->me_lfd, F_SETLK, &lock_info);
1265 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1269 struct flock lock_info;
1273 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1277 /* Try to get exclusive lock. If we succeed, then
1278 * nobody is using the lock region and we should initialize it.
1280 memset((void *)&lock_info, 0, sizeof(lock_info));
1281 lock_info.l_type = F_WRLCK;
1282 lock_info.l_whence = SEEK_SET;
1283 lock_info.l_start = 0;
1284 lock_info.l_len = 1;
1285 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1289 lock_info.l_type = F_RDLCK;
1290 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1296 size = lseek(env->me_lfd, 0, SEEK_END);
1297 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1298 if (size < rsize && *excl) {
1299 if (ftruncate(env->me_lfd, rsize) != 0) {
1305 size = rsize - sizeof(MDB_txninfo);
1306 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1308 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1310 if (env->me_txns == MAP_FAILED) {
1315 pthread_mutexattr_t mattr;
1317 pthread_mutexattr_init(&mattr);
1318 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1322 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1323 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1324 env->me_txns->mti_version = MDB_VERSION;
1325 env->me_txns->mti_magic = MDB_MAGIC;
1326 env->me_txns->mti_txnid = 0;
1327 env->me_txns->mti_numreaders = 0;
1328 env->me_txns->mti_me_toggle = 0;
1331 if (env->me_txns->mti_magic != MDB_MAGIC) {
1332 DPRINTF("lock region has invalid magic");
1336 if (env->me_txns->mti_version != MDB_VERSION) {
1337 DPRINTF("lock region is version %u, expected version %u",
1338 env->me_txns->mti_version, MDB_VERSION);
1339 rc = MDB_VERSION_MISMATCH;
1342 if (errno != EACCES && errno != EAGAIN) {
1356 #define LOCKNAME "/lock.mdb"
1357 #define DATANAME "/data.mdb"
1359 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1361 int oflags, rc, len, excl;
1362 char *lpath, *dpath;
1365 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1368 dpath = lpath + len + sizeof(LOCKNAME);
1369 sprintf(lpath, "%s" LOCKNAME, path);
1370 sprintf(dpath, "%s" DATANAME, path);
1372 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1376 if (F_ISSET(flags, MDB_RDONLY))
1379 oflags = O_RDWR | O_CREAT;
1381 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1386 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1387 /* synchronous fd for meta writes */
1388 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1390 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1395 env->me_path = strdup(path);
1396 DPRINTF("opened dbenv %p", (void *) env);
1397 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1399 mdb_env_share_locks(env);
1400 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1401 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1402 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1408 if (env->me_fd >= 0) {
1412 if (env->me_lfd >= 0) {
1422 mdb_env_close(MDB_env *env)
1427 free(env->me_dbs[1]);
1428 free(env->me_dbs[0]);
1432 pthread_key_delete(env->me_txkey);
1435 munmap(env->me_map, env->me_mapsize);
1440 pid_t pid = getpid();
1441 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1443 for (i=0; i<env->me_txns->mti_numreaders; i++)
1444 if (env->me_txns->mti_readers[i].mr_pid == pid)
1445 env->me_txns->mti_readers[i].mr_pid = 0;
1446 munmap(env->me_txns, size);
1452 /* Search for key within a leaf page, using binary search.
1453 * Returns the smallest entry larger or equal to the key.
1454 * If exactp is non-null, stores whether the found entry was an exact match
1455 * in *exactp (1 or 0).
1456 * If kip is non-null, stores the index of the found entry in *kip.
1457 * If no entry larger or equal to the key is found, returns NULL.
1460 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1461 int *exactp, unsigned int *kip)
1469 DPRINTF("searching %u keys in %s page %lu",
1471 IS_LEAF(mp) ? "leaf" : "branch",
1474 assert(NUMKEYS(mp) > 0);
1476 memset(&nodekey, 0, sizeof(nodekey));
1478 low = IS_LEAF(mp) ? 0 : 1;
1479 high = NUMKEYS(mp) - 1;
1480 while (low <= high) {
1481 i = (low + high) >> 1;
1482 node = NODEPTR(mp, i);
1484 nodekey.mv_size = node->mn_ksize;
1485 nodekey.mv_data = NODEKEY(node);
1487 if (txn->mt_dbxs[dbi].md_cmp)
1488 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1490 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1493 DPRINTF("found leaf index %u [%.*s], rc = %i",
1494 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1496 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1497 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1508 if (rc > 0) { /* Found entry is less than the key. */
1509 i++; /* Skip to get the smallest entry larger than key. */
1510 if (i >= NUMKEYS(mp))
1511 /* There is no entry larger or equal to the key. */
1515 *exactp = (rc == 0);
1516 if (kip) /* Store the key index if requested. */
1519 return NODEPTR(mp, i);
1523 cursor_pop_page(MDB_cursor *cursor)
1527 top = CURSOR_TOP(cursor);
1530 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1536 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1540 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1542 if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1544 ppage->mp_page = mp;
1545 CURSOR_PUSH(cursor, ppage);
1550 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1555 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1560 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1561 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1562 dp = txn->mt_u.dirty_list[x].mptr;
1568 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1570 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1576 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1577 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1579 MDB_page *mp = mpp->mp_page;
1582 if (cursor && cursor_push_page(cursor, mp) == NULL)
1585 while (IS_BRANCH(mp)) {
1589 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1590 assert(NUMKEYS(mp) > 1);
1591 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1593 if (key == NULL) /* Initialize cursor to first page. */
1595 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1596 /* cursor to last page */
1600 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1602 i = NUMKEYS(mp) - 1;
1610 DPRINTF("following index %u for key %.*s",
1611 i, (int)key->mv_size, (char *)key->mv_data);
1612 assert(i < NUMKEYS(mp));
1613 node = NODEPTR(mp, i);
1616 CURSOR_TOP(cursor)->mp_ki = i;
1618 mpp->mp_parent = mp;
1619 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1620 return MDB_PAGE_NOTFOUND;
1624 if (cursor && cursor_push_page(cursor, mp) == NULL)
1628 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1629 if ((rc = mdb_touch(txn, mpp)) != 0)
1631 dh = ((MDB_dhead *)mpp->mp_page)-1;
1632 dh->md_parent = mpp->mp_parent;
1633 dh->md_pi = mpp->mp_pi;
1640 DPRINTF("internal error, index points to a %02X page!?",
1642 return MDB_CORRUPTED;
1645 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1646 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1651 /* Search for the page a given key should be in.
1652 * Stores a pointer to the found page in *mpp.
1653 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1654 * If cursor is non-null, pushes parent pages on the cursor stack.
1655 * If modify is true, visited pages are updated with new page numbers.
1658 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1659 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1664 /* Choose which root page to start with. If a transaction is given
1665 * use the root page from the transaction, otherwise read the last
1666 * committed root page.
1668 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1669 DPRINTF("transaction has failed, must abort");
1672 root = txn->mt_dbs[dbi].md_root;
1674 if (root == P_INVALID) { /* Tree is empty. */
1675 DPRINTF("tree is empty");
1676 return MDB_NOTFOUND;
1679 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1680 return MDB_PAGE_NOTFOUND;
1682 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1685 /* For sub-databases, update main root first */
1686 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1688 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1692 txn->mt_dbxs[dbi].md_dirty = 1;
1694 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1695 mpp->mp_parent = NULL;
1697 if ((rc = mdb_touch(txn, mpp)))
1699 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1703 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1707 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1709 MDB_page *omp; /* overflow mpage */
1712 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1713 data->mv_size = leaf->mn_dsize;
1714 data->mv_data = NODEDATA(leaf);
1718 /* Read overflow data.
1720 data->mv_size = leaf->mn_dsize;
1721 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1722 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1723 DPRINTF("read overflow page %lu failed", pgno);
1724 return MDB_PAGE_NOTFOUND;
1726 data->mv_data = omp;
1732 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1733 MDB_val *key, MDB_val *data)
1741 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1743 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1746 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1750 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1753 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1754 if (leaf && exact) {
1755 /* Return first duplicate data item */
1756 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1759 mdb_xcursor_init0(txn, dbi, &mx);
1760 mdb_xcursor_init1(txn, dbi, &mx, leaf);
1761 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1762 if (rc != MDB_SUCCESS)
1764 leaf = NODEPTR(mpp.mp_page, 0);
1766 rc = mdb_read_data(txn, leaf, data);
1775 mdb_sibling(MDB_cursor *cursor, int move_right)
1779 MDB_ppage *parent, *top;
1782 top = CURSOR_TOP(cursor);
1783 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1784 return MDB_NOTFOUND; /* root has no siblings */
1787 DPRINTF("parent page is page %lu, index %u",
1788 parent->mp_page->mp_pgno, parent->mp_ki);
1790 cursor_pop_page(cursor);
1791 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1792 : (parent->mp_ki == 0)) {
1793 DPRINTF("no more keys left, moving to %s sibling",
1794 move_right ? "right" : "left");
1795 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1797 parent = CURSOR_TOP(cursor);
1803 DPRINTF("just moving to %s index key %u",
1804 move_right ? "right" : "left", parent->mp_ki);
1806 assert(IS_BRANCH(parent->mp_page));
1808 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1809 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1810 return MDB_PAGE_NOTFOUND;
1812 mp->parent = parent->mp_page;
1813 mp->parent_index = parent->mp_ki;
1816 cursor_push_page(cursor, mp);
1822 mdb_set_key(MDB_node *node, MDB_val *key)
1827 key->mv_size = node->mn_ksize;
1828 key->mv_data = NODEKEY(node);
1834 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1841 if (cursor->mc_eof) {
1842 return MDB_NOTFOUND;
1845 assert(cursor->mc_initialized);
1847 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1848 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1849 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1850 if (op != MDB_NEXT || rc == MDB_SUCCESS)
1855 top = CURSOR_TOP(cursor);
1858 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1860 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1861 DPRINTF("=====> move to next sibling page");
1862 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1864 return MDB_NOTFOUND;
1866 top = CURSOR_TOP(cursor);
1868 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1872 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1873 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1875 assert(IS_LEAF(mp));
1876 leaf = NODEPTR(mp, top->mp_ki);
1879 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1882 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1883 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1884 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1885 if (rc != MDB_SUCCESS)
1890 return mdb_set_key(leaf, key);
1894 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1901 assert(cursor->mc_initialized);
1903 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1904 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1905 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1906 if (op != MDB_PREV || rc == MDB_SUCCESS)
1911 top = CURSOR_TOP(cursor);
1914 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1916 if (top->mp_ki == 0) {
1917 DPRINTF("=====> move to prev sibling page");
1918 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1919 return MDB_NOTFOUND;
1921 top = CURSOR_TOP(cursor);
1923 top->mp_ki = NUMKEYS(mp) - 1;
1924 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1930 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1931 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1933 assert(IS_LEAF(mp));
1934 leaf = NODEPTR(mp, top->mp_ki);
1937 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1940 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1941 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1942 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1943 if (rc != MDB_SUCCESS)
1948 return mdb_set_key(leaf, key);
1952 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1953 MDB_cursor_op op, int *exactp)
1962 assert(key->mv_size > 0);
1964 while (CURSOR_TOP(cursor) != NULL)
1965 cursor_pop_page(cursor);
1967 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1968 if (rc != MDB_SUCCESS)
1970 assert(IS_LEAF(mpp.mp_page));
1972 top = CURSOR_TOP(cursor);
1973 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1974 if (exactp != NULL && !*exactp) {
1975 /* MDB_SET specified and not an exact match. */
1976 return MDB_NOTFOUND;
1980 DPRINTF("===> inexact leaf not found, goto sibling");
1981 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1982 return rc; /* no entries matched */
1983 top = CURSOR_TOP(cursor);
1985 mpp.mp_page = top->mp_page;
1986 assert(IS_LEAF(mpp.mp_page));
1987 leaf = NODEPTR(mpp.mp_page, 0);
1990 cursor->mc_initialized = 1;
1994 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1997 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1998 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1999 if (op == MDB_SET || op == MDB_SET_RANGE) {
2000 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2004 if (op == MDB_GET_BOTH) {
2009 op2 = MDB_SET_RANGE;
2011 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
2012 if (rc != MDB_SUCCESS)
2018 rc = mdb_set_key(leaf, key);
2019 if (rc == MDB_SUCCESS) {
2020 DPRINTF("==> cursor placed on key %.*s",
2021 (int)key->mv_size, (char *)key->mv_data);
2029 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2035 while (CURSOR_TOP(cursor) != NULL)
2036 cursor_pop_page(cursor);
2038 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2039 if (rc != MDB_SUCCESS)
2041 assert(IS_LEAF(mpp.mp_page));
2043 leaf = NODEPTR(mpp.mp_page, 0);
2044 cursor->mc_initialized = 1;
2048 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2051 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2052 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2053 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2058 return mdb_set_key(leaf, key);
2062 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2070 while (CURSOR_TOP(cursor) != NULL)
2071 cursor_pop_page(cursor);
2073 lkey.mv_size = MAXKEYSIZE+1;
2074 lkey.mv_data = NULL;
2076 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2077 if (rc != MDB_SUCCESS)
2079 assert(IS_LEAF(mpp.mp_page));
2081 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2082 cursor->mc_initialized = 1;
2085 top = CURSOR_TOP(cursor);
2086 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2089 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2092 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2093 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2094 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2100 return mdb_set_key(leaf, key);
2104 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2114 case MDB_GET_BOTH_RANGE:
2122 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2124 } else if (op != MDB_SET_RANGE)
2125 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2127 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2131 case MDB_NEXT_NODUP:
2132 if (!cursor->mc_initialized)
2133 rc = mdb_cursor_first(cursor, key, data);
2135 rc = mdb_cursor_next(cursor, key, data, op);
2139 case MDB_PREV_NODUP:
2140 if (!cursor->mc_initialized || cursor->mc_eof)
2141 rc = mdb_cursor_last(cursor, key, data);
2143 rc = mdb_cursor_prev(cursor, key, data, op);
2146 rc = mdb_cursor_first(cursor, key, data);
2149 rc = mdb_cursor_last(cursor, key, data);
2152 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2160 /* Allocate a page and initialize it
2163 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2167 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2169 DPRINTF("allocated new mpage %lu, page size %u",
2170 dp->p.mp_pgno, txn->mt_env->me_psize);
2171 dp->p.mp_flags = flags | P_DIRTY;
2172 dp->p.mp_lower = PAGEHDRSZ;
2173 dp->p.mp_upper = txn->mt_env->me_psize;
2175 if (IS_BRANCH(&dp->p))
2176 txn->mt_dbs[dbi].md_branch_pages++;
2177 else if (IS_LEAF(&dp->p))
2178 txn->mt_dbs[dbi].md_leaf_pages++;
2179 else if (IS_OVERFLOW(&dp->p)) {
2180 txn->mt_dbs[dbi].md_overflow_pages += num;
2181 dp->p.mp_pages = num;
2188 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2192 sz = LEAFSIZE(key, data);
2193 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2194 /* put on overflow page */
2195 sz -= data->mv_size - sizeof(pgno_t);
2198 return sz + sizeof(indx_t);
2202 mdb_branch_size(MDB_env *env, MDB_val *key)
2207 if (sz >= env->me_psize / MDB_MINKEYS) {
2208 /* put on overflow page */
2209 /* not implemented */
2210 /* sz -= key->size - sizeof(pgno_t); */
2213 return sz + sizeof(indx_t);
2217 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2218 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2221 size_t node_size = NODESIZE;
2224 MDB_dpage *ofp = NULL; /* overflow page */
2226 assert(mp->mp_upper >= mp->mp_lower);
2228 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2229 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2230 IS_LEAF(mp) ? "leaf" : "branch",
2231 mp->mp_pgno, indx, key ? key->mv_size : 0);
2234 node_size += key->mv_size;
2238 if (F_ISSET(flags, F_BIGDATA)) {
2239 /* Data already on overflow page. */
2240 node_size += sizeof(pgno_t);
2241 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2242 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2243 /* Put data on overflow page. */
2244 DPRINTF("data size is %zu, put on overflow page",
2246 node_size += sizeof(pgno_t);
2247 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2249 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2252 node_size += data->mv_size;
2256 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2257 DPRINTF("not enough room in page %lu, got %u ptrs",
2258 mp->mp_pgno, NUMKEYS(mp));
2259 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2260 mp->mp_upper - mp->mp_lower);
2261 DPRINTF("node size = %zu", node_size);
2265 /* Move higher pointers up one slot. */
2266 for (i = NUMKEYS(mp); i > indx; i--)
2267 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2269 /* Adjust free space offsets. */
2270 ofs = mp->mp_upper - node_size;
2271 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2272 mp->mp_ptrs[indx] = ofs;
2274 mp->mp_lower += sizeof(indx_t);
2276 /* Write the node data. */
2277 node = NODEPTR(mp, indx);
2278 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2279 node->mn_flags = flags;
2281 node->mn_dsize = data->mv_size;
2283 node->mn_pgno = pgno;
2286 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2291 if (F_ISSET(flags, F_BIGDATA))
2292 memcpy(node->mn_data + key->mv_size, data->mv_data,
2295 memcpy(node->mn_data + key->mv_size, data->mv_data,
2298 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2300 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2308 mdb_del_node(MDB_page *mp, indx_t indx)
2311 indx_t i, j, numkeys, ptr;
2315 DPRINTF("delete node %u on %s page %lu", indx,
2316 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2317 assert(indx < NUMKEYS(mp));
2319 node = NODEPTR(mp, indx);
2320 sz = NODESIZE + node->mn_ksize;
2322 if (F_ISSET(node->mn_flags, F_BIGDATA))
2323 sz += sizeof(pgno_t);
2325 sz += NODEDSZ(node);
2328 ptr = mp->mp_ptrs[indx];
2329 numkeys = NUMKEYS(mp);
2330 for (i = j = 0; i < numkeys; i++) {
2332 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2333 if (mp->mp_ptrs[i] < ptr)
2334 mp->mp_ptrs[j] += sz;
2339 base = (char *)mp + mp->mp_upper;
2340 memmove(base + sz, base, ptr - mp->mp_upper);
2342 mp->mp_lower -= sizeof(indx_t);
2347 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2352 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2353 mx->mx_txn.mt_dbs = mx->mx_dbs;
2354 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2355 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2357 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2362 mx->mx_dbxs[dbn+1].md_parent = dbn;
2363 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2364 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2365 mx->mx_dbxs[dbn+1].md_dirty = 0;
2366 mx->mx_txn.mt_numdbs = dbn+2;
2368 SLIST_INIT(&mx->mx_cursor.mc_stack);
2369 mx->mx_cursor.mc_txn = &mx->mx_txn;
2370 mx->mx_cursor.mc_dbi = dbn+1;
2374 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2376 MDB_db *db = NODEDATA(node);
2378 mx->mx_dbs[0] = txn->mt_dbs[0];
2379 mx->mx_dbs[1] = txn->mt_dbs[1];
2381 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2386 mx->mx_dbs[dbn] = *db;
2387 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2388 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2389 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2390 mx->mx_txn.mt_oldest = txn->mt_oldest;
2391 mx->mx_txn.mt_u = txn->mt_u;
2395 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2397 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2398 txn->mt_oldest = mx->mx_txn.mt_oldest;
2399 txn->mt_u = mx->mx_txn.mt_u;
2400 txn->mt_dbs[0] = mx->mx_dbs[0];
2401 txn->mt_dbs[1] = mx->mx_dbs[1];
2402 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2403 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2405 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2406 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2411 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2414 size_t size = sizeof(MDB_cursor);
2416 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2419 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2420 size += sizeof(MDB_xcursor);
2422 if ((cursor = calloc(1, size)) != NULL) {
2423 SLIST_INIT(&cursor->mc_stack);
2424 cursor->mc_dbi = dbi;
2425 cursor->mc_txn = txn;
2426 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2427 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2428 cursor->mc_xcursor = mx;
2429 mdb_xcursor_init0(txn, dbi, mx);
2440 /* Return the count of duplicate data items for the current key */
2442 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2444 if (mc == NULL || countp == NULL)
2447 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2450 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2453 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2458 mdb_cursor_close(MDB_cursor *cursor)
2460 if (cursor != NULL) {
2461 while(!CURSOR_EMPTY(cursor))
2462 cursor_pop_page(cursor);
2463 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2464 mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2465 while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2466 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2474 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2476 indx_t ptr, i, numkeys;
2482 node = NODEPTR(mp, indx);
2483 ptr = mp->mp_ptrs[indx];
2484 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2486 (int)node->mn_ksize, (char *)NODEKEY(node),
2487 (int)key->mv_size, (char *)key->mv_data,
2490 delta = key->mv_size - node->mn_ksize;
2492 if (delta > 0 && SIZELEFT(mp) < delta) {
2493 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2497 numkeys = NUMKEYS(mp);
2498 for (i = 0; i < numkeys; i++) {
2499 if (mp->mp_ptrs[i] <= ptr)
2500 mp->mp_ptrs[i] -= delta;
2503 base = (char *)mp + mp->mp_upper;
2504 len = ptr - mp->mp_upper + NODESIZE;
2505 memmove(base - delta, base, len);
2506 mp->mp_upper -= delta;
2508 node = NODEPTR(mp, indx);
2509 node->mn_ksize = key->mv_size;
2512 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2517 /* Move a node from src to dst.
2520 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2521 MDB_pageparent *dst, indx_t dstindx)
2527 srcnode = NODEPTR(src->mp_page, srcindx);
2528 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2529 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2531 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2532 src->mp_page->mp_pgno,
2533 dstindx, dst->mp_page->mp_pgno);
2535 /* Mark src and dst as dirty. */
2536 if ((rc = mdb_touch(txn, src)) ||
2537 (rc = mdb_touch(txn, dst)))
2540 /* Add the node to the destination page.
2542 key.mv_size = srcnode->mn_ksize;
2543 key.mv_data = NODEKEY(srcnode);
2544 data.mv_size = NODEDSZ(srcnode);
2545 data.mv_data = NODEDATA(srcnode);
2546 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2548 if (rc != MDB_SUCCESS)
2551 /* Delete the node from the source page.
2553 mdb_del_node(src->mp_page, srcindx);
2555 /* Update the parent separators.
2557 if (srcindx == 0 && src->mp_pi != 0) {
2558 DPRINTF("update separator for source page %lu to [%.*s]",
2559 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2560 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2561 &key)) != MDB_SUCCESS)
2565 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2567 nullkey.mv_size = 0;
2568 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2571 if (dstindx == 0 && dst->mp_pi != 0) {
2572 DPRINTF("update separator for destination page %lu to [%.*s]",
2573 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2574 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2575 &key)) != MDB_SUCCESS)
2579 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2581 nullkey.mv_size = 0;
2582 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2589 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2598 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2600 assert(txn != NULL);
2601 assert(src->mp_parent); /* can't merge root page */
2602 assert(dst->mp_parent);
2604 /* Mark src and dst as dirty. */
2605 if ((rc = mdb_touch(txn, src)) ||
2606 (rc = mdb_touch(txn, dst)))
2609 /* Move all nodes from src to dst.
2611 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2612 srcnode = NODEPTR(src->mp_page, i);
2614 key.mv_size = srcnode->mn_ksize;
2615 key.mv_data = NODEKEY(srcnode);
2616 data.mv_size = NODEDSZ(srcnode);
2617 data.mv_data = NODEDATA(srcnode);
2618 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2619 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2620 if (rc != MDB_SUCCESS)
2624 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2625 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2627 /* Unlink the src page from parent.
2629 mdb_del_node(src->mp_parent, src->mp_pi);
2630 if (src->mp_pi == 0) {
2632 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2636 if (IS_LEAF(src->mp_page))
2637 txn->mt_dbs[dbi].md_leaf_pages--;
2639 txn->mt_dbs[dbi].md_branch_pages--;
2641 mpp.mp_page = src->mp_parent;
2642 dh = (MDB_dhead *)src->mp_parent;
2644 mpp.mp_parent = dh->md_parent;
2645 mpp.mp_pi = dh->md_pi;
2647 return mdb_rebalance(txn, dbi, &mpp);
2650 #define FILL_THRESHOLD 250
2653 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2658 indx_t si = 0, di = 0;
2660 assert(txn != NULL);
2661 assert(mpp != NULL);
2663 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2664 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2665 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2667 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2668 DPRINTF("no need to rebalance page %lu, above fill threshold",
2669 mpp->mp_page->mp_pgno);
2673 if (mpp->mp_parent == NULL) {
2674 if (NUMKEYS(mpp->mp_page) == 0) {
2675 DPRINTF("tree is completely empty");
2676 txn->mt_dbs[dbi].md_root = P_INVALID;
2677 txn->mt_dbs[dbi].md_depth--;
2678 txn->mt_dbs[dbi].md_leaf_pages--;
2679 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2680 DPRINTF("collapsing root page!");
2681 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2682 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2683 return MDB_PAGE_NOTFOUND;
2684 txn->mt_dbs[dbi].md_depth--;
2685 txn->mt_dbs[dbi].md_branch_pages--;
2687 DPRINTF("root page doesn't need rebalancing");
2691 /* The parent (branch page) must have at least 2 pointers,
2692 * otherwise the tree is invalid.
2694 assert(NUMKEYS(mpp->mp_parent) > 1);
2696 /* Leaf page fill factor is below the threshold.
2697 * Try to move keys from left or right neighbor, or
2698 * merge with a neighbor page.
2703 if (mpp->mp_pi == 0) {
2704 /* We're the leftmost leaf in our parent.
2706 DPRINTF("reading right neighbor");
2707 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2708 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2709 return MDB_PAGE_NOTFOUND;
2710 npp.mp_pi = mpp->mp_pi + 1;
2712 di = NUMKEYS(mpp->mp_page);
2714 /* There is at least one neighbor to the left.
2716 DPRINTF("reading left neighbor");
2717 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2718 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2719 return MDB_PAGE_NOTFOUND;
2720 npp.mp_pi = mpp->mp_pi - 1;
2721 si = NUMKEYS(npp.mp_page) - 1;
2724 npp.mp_parent = mpp->mp_parent;
2726 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2727 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2729 /* If the neighbor page is above threshold and has at least two
2730 * keys, move one key from it.
2732 * Otherwise we should try to merge them.
2734 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2735 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2736 else { /* FIXME: if (has_enough_room()) */
2737 if (mpp->mp_pi == 0)
2738 return mdb_merge(txn, dbi, &npp, mpp);
2740 return mdb_merge(txn, dbi, mpp, &npp);
2745 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2749 /* add overflow pages to free list */
2750 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2754 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2755 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2756 for (i=0; i<ovpages; i++) {
2757 DPRINTF("freed ov page %lu", pg);
2758 mdb_midl_insert(txn->mt_free_pgs, pg);
2762 mdb_del_node(mpp->mp_page, ki);
2763 txn->mt_dbs[dbi].md_entries--;
2764 rc = mdb_rebalance(txn, dbi, mpp);
2765 if (rc != MDB_SUCCESS)
2766 txn->mt_flags |= MDB_TXN_ERROR;
2772 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2773 MDB_val *key, MDB_val *data,
2781 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2783 assert(key != NULL);
2785 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2788 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2792 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2796 mpp.mp_parent = NULL;
2798 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2801 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2802 if (leaf == NULL || !exact) {
2803 return MDB_NOTFOUND;
2806 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2810 mdb_xcursor_init0(txn, dbi, &mx);
2811 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2812 if (flags == MDB_DEL_DUP) {
2813 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2814 mdb_xcursor_fini(txn, dbi, &mx);
2815 if (rc != MDB_SUCCESS)
2817 /* If sub-DB still has entries, we're done */
2818 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2819 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2823 /* otherwise fall thru and delete the sub-DB */
2825 /* add all the child DB's pages to the free list */
2826 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2827 NULL, &mx.mx_cursor, 0, &mp2);
2828 if (rc == MDB_SUCCESS) {
2829 MDB_ppage *top, *parent;
2833 cursor_pop_page(&mx.mx_cursor);
2834 top = CURSOR_TOP(&mx.mx_cursor);
2836 parent = SLIST_NEXT(top, mp_entry);
2837 while (parent != NULL) {
2838 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2839 ni = NODEPTR(top->mp_page, i);
2840 mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2844 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2845 cursor_pop_page(&mx.mx_cursor);
2846 top = CURSOR_TOP(&mx.mx_cursor);
2847 parent = SLIST_NEXT(top, mp_entry);
2849 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2850 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2855 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2860 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2863 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2866 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2867 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2868 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2869 * refer to a node in the new right sibling page.
2872 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2873 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2876 int rc = MDB_SUCCESS, ins_new = 0;
2879 unsigned int i, j, split_indx;
2881 MDB_val sepkey, rkey, rdata;
2883 MDB_dpage *mdp, *rdp, *pdp;
2886 assert(txn != NULL);
2888 dh = ((MDB_dhead *)*mpp) - 1;
2889 mdp = (MDB_dpage *)dh;
2890 newindx = *newindxp;
2892 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2893 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2894 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2896 if (mdp->h.md_parent == NULL) {
2897 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2900 mdp->h.md_parent = &pdp->p;
2901 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2902 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2903 txn->mt_dbs[dbi].md_depth++;
2905 /* Add left (implicit) pointer. */
2906 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2907 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
2910 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2913 /* Create a right sibling. */
2914 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2916 rdp->h.md_parent = mdp->h.md_parent;
2917 rdp->h.md_pi = mdp->h.md_pi + 1;
2918 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2920 /* Move half of the keys to the right sibling. */
2921 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2923 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2924 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2925 mdp->p.mp_lower = PAGEHDRSZ;
2926 mdp->p.mp_upper = txn->mt_env->me_psize;
2928 split_indx = NUMKEYS(copy) / 2 + 1;
2930 /* First find the separating key between the split pages.
2932 memset(&sepkey, 0, sizeof(sepkey));
2933 if (newindx == split_indx) {
2934 sepkey.mv_size = newkey->mv_size;
2935 sepkey.mv_data = newkey->mv_data;
2937 node = NODEPTR(copy, split_indx);
2938 sepkey.mv_size = node->mn_ksize;
2939 sepkey.mv_data = NODEKEY(node);
2942 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2944 /* Copy separator key to the parent.
2946 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2947 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2948 &sepkey, NULL, rdp->p.mp_pgno);
2950 /* Right page might now have changed parent.
2951 * Check if left page also changed parent.
2953 if (rdp->h.md_parent != mdp->h.md_parent &&
2954 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2955 mdp->h.md_parent = rdp->h.md_parent;
2956 mdp->h.md_pi = rdp->h.md_pi - 1;
2959 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2960 &sepkey, NULL, rdp->p.mp_pgno, 0);
2962 if (rc != MDB_SUCCESS) {
2967 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2968 if (i < split_indx) {
2969 /* Re-insert in left sibling. */
2972 /* Insert in right sibling. */
2973 if (i == split_indx)
2974 /* Reset insert index for right sibling. */
2975 j = (i == newindx && ins_new);
2979 if (i == newindx && !ins_new) {
2980 /* Insert the original entry that caused the split. */
2981 rkey.mv_data = newkey->mv_data;
2982 rkey.mv_size = newkey->mv_size;
2983 if (IS_LEAF(&mdp->p)) {
2984 rdata.mv_data = newdata->mv_data;
2985 rdata.mv_size = newdata->mv_size;
2992 /* Update page and index for the new key. */
2995 } else if (i == NUMKEYS(copy)) {
2998 node = NODEPTR(copy, i);
2999 rkey.mv_data = NODEKEY(node);
3000 rkey.mv_size = node->mn_ksize;
3001 if (IS_LEAF(&mdp->p)) {
3002 rdata.mv_data = NODEDATA(node);
3003 rdata.mv_size = node->mn_dsize;
3005 pgno = node->mn_pgno;
3006 flags = node->mn_flags;
3011 if (!IS_LEAF(&mdp->p) && j == 0) {
3012 /* First branch index doesn't need key data. */
3016 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
3024 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3025 MDB_val *key, MDB_val *data, unsigned int flags)
3027 int rc = MDB_SUCCESS, exact;
3031 MDB_val xdata, *rdata;
3034 DPRINTF("==> put key %.*s, size %zu, data size %zu",
3035 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
3037 mpp.mp_parent = NULL;
3039 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3040 if (rc == MDB_SUCCESS) {
3041 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3042 if (leaf && exact) {
3043 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3046 if (flags == MDB_NOOVERWRITE) {
3047 DPRINTF("duplicate key %.*s",
3048 (int)key->mv_size, (char *)key->mv_data);
3049 return MDB_KEYEXIST;
3051 /* same size, just replace it */
3052 if (NODEDSZ(leaf) == data->mv_size) {
3053 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3056 mdb_del_node(mpp.mp_page, ki);
3058 if (leaf == NULL) { /* append if not found */
3059 ki = NUMKEYS(mpp.mp_page);
3060 DPRINTF("appending key at index %i", ki);
3062 } else if (rc == MDB_NOTFOUND) {
3064 /* new file, just write a root leaf page */
3065 DPRINTF("allocating new root leaf page");
3066 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3069 mpp.mp_page = &dp->p;
3070 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3071 txn->mt_dbs[dbi].md_depth++;
3077 assert(IS_LEAF(mpp.mp_page));
3078 DPRINTF("there are %u keys, should insert new key at index %i",
3079 NUMKEYS(mpp.mp_page), ki);
3081 /* For sorted dups, the data item at this level is a DB record
3082 * for a child DB; the actual data elements are stored as keys
3085 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3087 xdata.mv_size = sizeof(MDB_db);
3088 xdata.mv_data = &dummy;
3089 memset(&dummy, 0, sizeof(dummy));
3090 dummy.md_root = P_INVALID;
3095 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3096 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3098 /* There is room already in this leaf page. */
3099 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3102 if (rc != MDB_SUCCESS)
3103 txn->mt_flags |= MDB_TXN_ERROR;
3105 txn->mt_dbs[dbi].md_entries++;
3107 /* Remember if we just added a subdatabase */
3108 if (flags & F_SUBDATA) {
3109 leaf = NODEPTR(mpp.mp_page, ki);
3110 leaf->mn_flags |= F_SUBDATA;
3113 /* Now store the actual data in the child DB. Note that we're
3114 * storing the user data in the keys field, so there are strict
3115 * size limits on dupdata. The actual data fields of the child
3116 * DB are all zero size.
3118 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3121 leaf = NODEPTR(mpp.mp_page, ki);
3123 mdb_xcursor_init0(txn, dbi, &mx);
3124 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3127 if (flags == MDB_NODUPDATA)
3128 flags = MDB_NOOVERWRITE;
3129 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3130 mdb_xcursor_fini(txn, dbi, &mx);
3131 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3141 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3142 MDB_val *key, MDB_val *data, unsigned int flags)
3144 assert(key != NULL);
3145 assert(data != NULL);
3147 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3150 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3154 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3158 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3161 return mdb_put0(txn, dbi, key, data, flags);
3165 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3170 *arg = env->me_flags;
3175 mdb_env_get_path(MDB_env *env, const char **arg)
3180 *arg = env->me_path;
3185 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3187 arg->ms_psize = env->me_psize;
3188 arg->ms_depth = db->md_depth;
3189 arg->ms_branch_pages = db->md_branch_pages;
3190 arg->ms_leaf_pages = db->md_leaf_pages;
3191 arg->ms_overflow_pages = db->md_overflow_pages;
3192 arg->ms_entries = db->md_entries;
3197 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3199 if (env == NULL || arg == NULL)
3202 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3205 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3215 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3216 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3220 /* Is the DB already open? */
3222 for (i=2; i<txn->mt_numdbs; i++) {
3223 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3224 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3230 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3233 /* Find the DB info */
3235 key.mv_data = (void *)name;
3236 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3238 /* Create if requested */
3239 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3241 data.mv_size = sizeof(MDB_db);
3242 data.mv_data = &dummy;
3243 memset(&dummy, 0, sizeof(dummy));
3244 dummy.md_root = P_INVALID;
3245 dummy.md_flags = flags & 0xffff;
3246 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3250 /* OK, got info, add to table */
3251 if (rc == MDB_SUCCESS) {
3252 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3253 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3254 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3255 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3256 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3257 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3258 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3259 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3260 *dbi = txn->mt_numdbs;
3267 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3269 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3272 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3275 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3278 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3280 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3281 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3282 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3286 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3288 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3291 txn->mt_dbxs[dbi].md_cmp = cmp;
3295 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3297 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3300 txn->mt_dbxs[dbi].md_dcmp = cmp;
3304 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3306 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3309 txn->mt_dbxs[dbi].md_rel = rel;