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 */
143 void * p_align; /* for IL32P64 */
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;
463 static const char *errstr[] = {
464 "MDB_KEYEXIST: Key/data pair already exists",
465 "MDB_NOTFOUND: No matching key/data pair found",
466 "MDB_PAGE_NOTFOUND: Requested page not found",
467 "MDB_CORRUPTED: Located page was wrong type",
468 "MDB_PANIC: Update of meta page failed",
469 "MDB_VERSION_MISMATCH: Database environment version mismatch"
473 mdb_strerror(int err)
476 return ("Successful return: 0");
478 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
479 return (char *)errstr[err - MDB_KEYEXIST];
481 return strerror(err);
485 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
487 return txn->mt_dbxs[dbi].md_cmp(a, b);
491 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
493 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
494 #if __BYTE_ORDER == __LITTLE_ENDIAN
498 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
500 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
503 /* Allocate new page(s) for writing */
505 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
508 pgno_t pgno = P_INVALID;
512 if (txn->mt_txnid > 2) {
514 oldest = txn->mt_txnid - 2;
515 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
516 /* See if there's anything in the free DB */
521 mpp.mp_parent = NULL;
523 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
524 leaf = NODEPTR(mpp.mp_page, 0);
525 kptr = (ULONG *)NODEKEY(leaf);
527 /* It's potentially usable, unless there are still
528 * older readers outstanding. Grab it.
530 if (oldest > *kptr) {
535 mdb_read_data(txn, leaf, &data);
536 idl = (ULONG *)data.mv_data;
537 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
538 mop->mo_next = txn->mt_env->me_pghead;
539 mop->mo_txnid = *kptr;
540 txn->mt_env->me_pghead = mop;
541 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
546 DPRINTF("IDL read txn %lu root %lu num %lu",
547 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
548 for (i=0; i<idl[0]; i++) {
549 DPRINTF("IDL %lu", idl[i+1]);
553 /* drop this IDL from the DB */
554 mpp.mp_parent = NULL;
556 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
557 leaf = NODEPTR(mpp.mp_page, 0);
558 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
561 if (txn->mt_env->me_pghead) {
563 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
564 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
567 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
569 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
570 MDB_oldpages *mop = txn->mt_env->me_pghead;
571 txn->mt_oldest = oldest;
573 /* FIXME: For now, always use fresh pages. We
574 * really ought to search the free list for a
579 /* peel pages off tail, so we only have to truncate the list */
580 pgno = MDB_IDL_LAST(mop->mo_pages);
581 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
583 if (mop->mo_pages[2] > mop->mo_pages[1])
584 mop->mo_pages[0] = 0;
588 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
589 txn->mt_env->me_pghead = mop->mo_next;
597 if (pgno == P_INVALID) {
598 /* DB size is maxed out */
599 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
602 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
605 dp->h.md_parent = parent;
606 dp->h.md_pi = parent_idx;
607 if (pgno == P_INVALID) {
608 dp->p.mp_pgno = txn->mt_next_pgno;
609 txn->mt_next_pgno += num;
611 dp->p.mp_pgno = pgno;
613 mid.mid = dp->p.mp_pgno;
615 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
620 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
623 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
625 MDB_page *mp = pp->mp_page;
630 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
632 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
634 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
635 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
636 pgno = dp->p.mp_pgno;
637 memcpy(&dp->p, mp, txn->mt_env->me_psize);
640 mp->mp_flags |= P_DIRTY;
642 /* Update the page number to new touched page. */
643 if (pp->mp_parent != NULL)
644 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
651 mdb_env_sync(MDB_env *env, int force)
654 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
655 if (fdatasync(env->me_fd))
662 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
667 if (env->me_flags & MDB_FATAL_ERROR) {
668 DPRINTF("mdb_txn_begin: environment had fatal error, must shutdown!");
671 if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
672 DPRINTF("calloc: %s", strerror(errno));
677 txn->mt_flags |= MDB_TXN_RDONLY;
679 txn->mt_u.dirty_list = env->me_dirty_list;
680 txn->mt_u.dirty_list[0].mid = 0;
681 txn->mt_free_pgs = env->me_free_pgs;
682 txn->mt_free_pgs[0] = 0;
684 pthread_mutex_lock(&env->me_txns->mti_wmutex);
685 env->me_txns->mti_txnid++;
688 txn->mt_txnid = env->me_txns->mti_txnid;
690 MDB_reader *r = pthread_getspecific(env->me_txkey);
693 pthread_mutex_lock(&env->me_txns->mti_mutex);
694 for (i=0; i<env->me_txns->mti_numreaders; i++)
695 if (env->me_txns->mti_readers[i].mr_pid == 0)
697 if (i == env->me_maxreaders) {
698 pthread_mutex_unlock(&env->me_txns->mti_mutex);
701 env->me_txns->mti_readers[i].mr_pid = getpid();
702 env->me_txns->mti_readers[i].mr_tid = pthread_self();
703 r = &env->me_txns->mti_readers[i];
704 pthread_setspecific(env->me_txkey, r);
705 if (i >= env->me_txns->mti_numreaders)
706 env->me_txns->mti_numreaders = i+1;
707 pthread_mutex_unlock(&env->me_txns->mti_mutex);
709 r->mr_txnid = txn->mt_txnid;
710 txn->mt_u.reader = r;
717 toggle = env->me_txns->mti_me_toggle;
718 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
723 /* Copy the DB arrays */
724 txn->mt_numdbs = env->me_numdbs;
725 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
726 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
727 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
728 if (txn->mt_numdbs > 2)
729 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
730 (txn->mt_numdbs - 2) * sizeof(MDB_db));
734 txn->mt_flags |= MDB_TXN_METOGGLE;
735 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
738 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
739 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
746 mdb_txn_abort(MDB_txn *txn)
754 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
755 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
759 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
760 txn->mt_u.reader->mr_txnid = 0;
765 /* Discard all dirty pages. */
766 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
767 free(txn->mt_u.dirty_list[i].mptr);
769 while ((mop = txn->mt_env->me_pghead)) {
770 txn->mt_env->me_pghead = mop->mo_next;
775 env->me_txns->mti_txnid--;
776 for (i=2; i<env->me_numdbs; i++)
777 env->me_dbxs[i].md_dirty = 0;
778 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
785 mdb_txn_commit(MDB_txn *txn)
794 struct iovec iov[MDB_COMMIT_PAGES];
797 assert(txn->mt_env != NULL);
801 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
806 if (txn != env->me_txn) {
807 DPRINTF("attempt to commit unknown transaction");
812 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
813 DPRINTF("error flag is set, can't commit");
818 if (!txn->mt_u.dirty_list[0].mid)
821 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
822 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
824 /* should only be one record now */
825 if (env->me_pghead) {
829 mop = env->me_pghead;
830 key.mv_size = sizeof(pgno_t);
831 key.mv_data = (char *)&mop->mo_txnid;
832 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
833 data.mv_data = mop->mo_pages;
834 mdb_put0(txn, FREE_DBI, &key, &data, 0);
835 free(env->me_pghead);
836 env->me_pghead = NULL;
838 /* save to free list */
839 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
843 /* make sure last page of freeDB is touched and on freelist */
844 key.mv_size = MAXKEYSIZE+1;
846 mpp.mp_parent = NULL;
848 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
853 ULONG *idl = txn->mt_free_pgs;
854 DPRINTF("IDL write txn %lu root %lu num %lu",
855 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
856 for (i=0; i<idl[0]; i++) {
857 DPRINTF("IDL %lu", idl[i+1]);
861 /* write to last page of freeDB */
862 key.mv_size = sizeof(pgno_t);
863 key.mv_data = (char *)&txn->mt_txnid;
864 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
865 data.mv_data = txn->mt_free_pgs;
866 mdb_put0(txn, FREE_DBI, &key, &data, 0);
869 /* Update DB root pointers. Their pages have already been
870 * touched so this is all in-place and cannot fail.
874 data.mv_size = sizeof(MDB_db);
876 for (i = 2; i < txn->mt_numdbs; i++) {
877 if (txn->mt_dbxs[i].md_dirty) {
878 data.mv_data = &txn->mt_dbs[i];
879 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
884 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
891 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
892 dp = txn->mt_u.dirty_list[i].mptr;
893 if (dp->p.mp_pgno != next) {
895 DPRINTF("committing %u dirty pages", n);
896 rc = writev(env->me_fd, iov, n);
900 DPRINTF("short write, filesystem full?");
902 DPRINTF("writev: %s", strerror(errno));
909 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
910 next = dp->p.mp_pgno;
912 DPRINTF("committing page %lu", dp->p.mp_pgno);
913 iov[n].iov_len = env->me_psize * dp->h.md_num;
914 iov[n].iov_base = &dp->p;
915 size += iov[n].iov_len;
916 next = dp->p.mp_pgno + dp->h.md_num;
917 /* clear dirty flag */
918 dp->p.mp_flags &= ~P_DIRTY;
919 if (++n >= MDB_COMMIT_PAGES) {
928 DPRINTF("committing %u dirty pages", n);
929 rc = writev(env->me_fd, iov, n);
933 DPRINTF("short write, filesystem full?");
935 DPRINTF("writev: %s", strerror(errno));
942 /* Drop the dirty pages.
944 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++)
945 free(txn->mt_u.dirty_list[i].mptr);
947 if ((n = mdb_env_sync(env, 0)) != 0 ||
948 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
955 /* update the DB tables */
957 int toggle = !env->me_db_toggle;
959 for (i = 2; i < env->me_numdbs; i++) {
960 if (txn->mt_dbxs[i].md_dirty) {
961 env->me_dbs[toggle][i] = txn->mt_dbs[i];
962 txn->mt_dbxs[i].md_dirty = 0;
965 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
966 txn->mt_dbxs[i].md_dirty = 0;
967 env->me_dbxs[i] = txn->mt_dbxs[i];
968 env->me_dbs[toggle][i] = txn->mt_dbs[i];
970 env->me_db_toggle = toggle;
971 env->me_numdbs = txn->mt_numdbs;
976 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
986 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
995 /* We don't know the page size yet, so use a minimum value.
998 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1000 } else if (rc != PAGESIZE) {
1003 DPRINTF("read: %s", strerror(errno));
1007 p = (MDB_page *)page;
1009 if (!F_ISSET(p->mp_flags, P_META)) {
1010 DPRINTF("page %lu not a meta page", p->mp_pgno);
1015 if (m->mm_magic != MDB_MAGIC) {
1016 DPRINTF("meta has invalid magic");
1020 if (m->mm_version != MDB_VERSION) {
1021 DPRINTF("database is version %u, expected version %u",
1022 m->mm_version, MDB_VERSION);
1023 return MDB_VERSION_MISMATCH;
1026 memcpy(meta, m, sizeof(*m));
1031 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1038 DPRINTF("writing new meta page");
1039 psize = sysconf(_SC_PAGE_SIZE);
1041 meta->mm_magic = MDB_MAGIC;
1042 meta->mm_version = MDB_VERSION;
1043 meta->mm_psize = psize;
1044 meta->mm_last_pg = 1;
1045 meta->mm_flags = env->me_flags & 0xffff;
1046 meta->mm_flags |= MDB_INTEGERKEY;
1047 meta->mm_dbs[0].md_root = P_INVALID;
1048 meta->mm_dbs[1].md_root = P_INVALID;
1050 p = calloc(2, psize);
1052 p->mp_flags = P_META;
1055 memcpy(m, meta, sizeof(*meta));
1057 q = (MDB_page *)((char *)p + psize);
1060 q->mp_flags = P_META;
1063 memcpy(m, meta, sizeof(*meta));
1065 rc = write(env->me_fd, p, psize * 2);
1067 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1071 mdb_env_write_meta(MDB_txn *txn)
1074 MDB_meta meta, metab;
1076 int rc, len, toggle;
1079 assert(txn != NULL);
1080 assert(txn->mt_env != NULL);
1082 toggle = !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE);
1083 DPRINTF("writing meta page %d for root page %lu",
1084 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1088 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1089 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1091 ptr = (char *)&meta;
1092 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1093 len = sizeof(MDB_meta) - off;
1096 meta.mm_dbs[0] = txn->mt_dbs[0];
1097 meta.mm_dbs[1] = txn->mt_dbs[1];
1098 meta.mm_last_pg = txn->mt_next_pgno - 1;
1099 meta.mm_txnid = txn->mt_txnid;
1102 off += env->me_psize;
1105 /* Write to the SYNC fd */
1106 rc = pwrite(env->me_mfd, ptr, len, off);
1108 DPRINTF("write failed, disk error?");
1109 /* On a failure, the pagecache still contains the new data.
1110 * Write some old data back, to prevent it from being used.
1111 * Use the non-SYNC fd; we know it will fail anyway.
1113 meta.mm_last_pg = metab.mm_last_pg;
1114 meta.mm_txnid = metab.mm_txnid;
1115 rc = pwrite(env->me_fd, ptr, len, off);
1116 env->me_flags |= MDB_FATAL_ERROR;
1119 txn->mt_env->me_txns->mti_me_toggle = toggle;
1125 mdb_env_read_meta(MDB_env *env, int *which)
1129 assert(env != NULL);
1133 else if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1136 if (env->me_meta != env->me_metas[toggle])
1137 env->me_meta = env->me_metas[toggle];
1139 DPRINTF("Using meta page %d", toggle);
1145 mdb_env_create(MDB_env **env)
1149 e = calloc(1, sizeof(MDB_env));
1150 if (!e) return ENOMEM;
1152 e->me_maxreaders = DEFAULT_READERS;
1162 mdb_env_set_mapsize(MDB_env *env, size_t size)
1166 env->me_mapsize = size;
1171 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1173 env->me_maxdbs = dbs;
1178 mdb_env_set_maxreaders(MDB_env *env, int readers)
1180 env->me_maxreaders = readers;
1185 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1187 if (!env || !readers)
1189 *readers = env->me_maxreaders;
1194 mdb_env_open2(MDB_env *env, unsigned int flags)
1200 env->me_flags = flags;
1202 memset(&meta, 0, sizeof(meta));
1204 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1207 DPRINTF("new mdbenv");
1211 if (!env->me_mapsize) {
1212 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1216 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1218 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1220 if (env->me_map == MAP_FAILED)
1224 meta.mm_mapsize = env->me_mapsize;
1225 if (flags & MDB_FIXEDMAP)
1226 meta.mm_address = env->me_map;
1227 i = mdb_env_init_meta(env, &meta);
1228 if (i != MDB_SUCCESS) {
1229 munmap(env->me_map, env->me_mapsize);
1233 env->me_psize = meta.mm_psize;
1235 env->me_maxpg = env->me_mapsize / env->me_psize;
1237 p = (MDB_page *)env->me_map;
1238 env->me_metas[0] = METADATA(p);
1239 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1241 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1244 DPRINTF("opened database version %u, pagesize %u",
1245 env->me_meta->mm_version, env->me_psize);
1246 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1247 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1248 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1249 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1250 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1251 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1257 mdb_env_reader_dest(void *ptr)
1259 MDB_reader *reader = ptr;
1261 reader->mr_txnid = 0;
1266 /* downgrade the exclusive lock on the region back to shared */
1268 mdb_env_share_locks(MDB_env *env)
1270 struct flock lock_info;
1272 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1273 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1274 env->me_txns->mti_me_toggle = 1;
1276 memset((void *)&lock_info, 0, sizeof(lock_info));
1277 lock_info.l_type = F_RDLCK;
1278 lock_info.l_whence = SEEK_SET;
1279 lock_info.l_start = 0;
1280 lock_info.l_len = 1;
1281 fcntl(env->me_lfd, F_SETLK, &lock_info);
1285 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1289 struct flock lock_info;
1293 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1297 /* Try to get exclusive lock. If we succeed, then
1298 * nobody is using the lock region and we should initialize it.
1300 memset((void *)&lock_info, 0, sizeof(lock_info));
1301 lock_info.l_type = F_WRLCK;
1302 lock_info.l_whence = SEEK_SET;
1303 lock_info.l_start = 0;
1304 lock_info.l_len = 1;
1305 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1309 lock_info.l_type = F_RDLCK;
1310 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1316 size = lseek(env->me_lfd, 0, SEEK_END);
1317 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1318 if (size < rsize && *excl) {
1319 if (ftruncate(env->me_lfd, rsize) != 0) {
1325 size = rsize - sizeof(MDB_txninfo);
1326 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1328 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1330 if (env->me_txns == MAP_FAILED) {
1335 pthread_mutexattr_t mattr;
1337 pthread_mutexattr_init(&mattr);
1338 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1342 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1343 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1344 env->me_txns->mti_version = MDB_VERSION;
1345 env->me_txns->mti_magic = MDB_MAGIC;
1346 env->me_txns->mti_txnid = 0;
1347 env->me_txns->mti_numreaders = 0;
1348 env->me_txns->mti_me_toggle = 0;
1351 if (env->me_txns->mti_magic != MDB_MAGIC) {
1352 DPRINTF("lock region has invalid magic");
1356 if (env->me_txns->mti_version != MDB_VERSION) {
1357 DPRINTF("lock region is version %u, expected version %u",
1358 env->me_txns->mti_version, MDB_VERSION);
1359 rc = MDB_VERSION_MISMATCH;
1362 if (errno != EACCES && errno != EAGAIN) {
1376 #define LOCKNAME "/lock.mdb"
1377 #define DATANAME "/data.mdb"
1379 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1381 int oflags, rc, len, excl;
1382 char *lpath, *dpath;
1385 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1388 dpath = lpath + len + sizeof(LOCKNAME);
1389 sprintf(lpath, "%s" LOCKNAME, path);
1390 sprintf(dpath, "%s" DATANAME, path);
1392 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1396 if (F_ISSET(flags, MDB_RDONLY))
1399 oflags = O_RDWR | O_CREAT;
1401 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1406 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1407 /* synchronous fd for meta writes */
1408 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1410 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1415 env->me_path = strdup(path);
1416 DPRINTF("opened dbenv %p", (void *) env);
1417 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1419 mdb_env_share_locks(env);
1420 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1421 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1422 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1428 if (env->me_fd >= 0) {
1432 if (env->me_lfd >= 0) {
1442 mdb_env_close(MDB_env *env)
1447 free(env->me_dbs[1]);
1448 free(env->me_dbs[0]);
1452 pthread_key_delete(env->me_txkey);
1455 munmap(env->me_map, env->me_mapsize);
1460 pid_t pid = getpid();
1461 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1463 for (i=0; i<env->me_txns->mti_numreaders; i++)
1464 if (env->me_txns->mti_readers[i].mr_pid == pid)
1465 env->me_txns->mti_readers[i].mr_pid = 0;
1466 munmap(env->me_txns, size);
1472 /* Search for key within a leaf page, using binary search.
1473 * Returns the smallest entry larger or equal to the key.
1474 * If exactp is non-null, stores whether the found entry was an exact match
1475 * in *exactp (1 or 0).
1476 * If kip is non-null, stores the index of the found entry in *kip.
1477 * If no entry larger or equal to the key is found, returns NULL.
1480 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1481 int *exactp, unsigned int *kip)
1489 DPRINTF("searching %u keys in %s page %lu",
1491 IS_LEAF(mp) ? "leaf" : "branch",
1494 assert(NUMKEYS(mp) > 0);
1496 memset(&nodekey, 0, sizeof(nodekey));
1498 low = IS_LEAF(mp) ? 0 : 1;
1499 high = NUMKEYS(mp) - 1;
1500 while (low <= high) {
1501 i = (low + high) >> 1;
1502 node = NODEPTR(mp, i);
1504 nodekey.mv_size = node->mn_ksize;
1505 nodekey.mv_data = NODEKEY(node);
1507 if (txn->mt_dbxs[dbi].md_cmp)
1508 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1510 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1513 DPRINTF("found leaf index %u [%.*s], rc = %i",
1514 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1516 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1517 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1528 if (rc > 0) { /* Found entry is less than the key. */
1529 i++; /* Skip to get the smallest entry larger than key. */
1530 if (i >= NUMKEYS(mp))
1531 /* There is no entry larger or equal to the key. */
1535 *exactp = (rc == 0);
1536 if (kip) /* Store the key index if requested. */
1539 return NODEPTR(mp, i);
1543 cursor_pop_page(MDB_cursor *cursor)
1547 top = CURSOR_TOP(cursor);
1550 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1556 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1560 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1562 if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1564 ppage->mp_page = mp;
1565 CURSOR_PUSH(cursor, ppage);
1570 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1575 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1580 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1581 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1582 dp = txn->mt_u.dirty_list[x].mptr;
1588 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1590 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1596 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1597 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1599 MDB_page *mp = mpp->mp_page;
1602 if (cursor && cursor_push_page(cursor, mp) == NULL)
1605 while (IS_BRANCH(mp)) {
1609 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1610 assert(NUMKEYS(mp) > 1);
1611 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1613 if (key == NULL) /* Initialize cursor to first page. */
1615 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1616 /* cursor to last page */
1620 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1622 i = NUMKEYS(mp) - 1;
1630 DPRINTF("following index %u for key %.*s",
1631 i, (int)key->mv_size, (char *)key->mv_data);
1632 assert(i < NUMKEYS(mp));
1633 node = NODEPTR(mp, i);
1636 CURSOR_TOP(cursor)->mp_ki = i;
1638 mpp->mp_parent = mp;
1639 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1640 return MDB_PAGE_NOTFOUND;
1644 if (cursor && cursor_push_page(cursor, mp) == NULL)
1648 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1649 if ((rc = mdb_touch(txn, mpp)) != 0)
1651 dh = ((MDB_dhead *)mpp->mp_page)-1;
1652 dh->md_parent = mpp->mp_parent;
1653 dh->md_pi = mpp->mp_pi;
1660 DPRINTF("internal error, index points to a %02X page!?",
1662 return MDB_CORRUPTED;
1665 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1666 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1671 /* Search for the page a given key should be in.
1672 * Stores a pointer to the found page in *mpp.
1673 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1674 * If cursor is non-null, pushes parent pages on the cursor stack.
1675 * If modify is true, visited pages are updated with new page numbers.
1678 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1679 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1684 /* Choose which root page to start with. If a transaction is given
1685 * use the root page from the transaction, otherwise read the last
1686 * committed root page.
1688 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1689 DPRINTF("transaction has failed, must abort");
1692 root = txn->mt_dbs[dbi].md_root;
1694 if (root == P_INVALID) { /* Tree is empty. */
1695 DPRINTF("tree is empty");
1696 return MDB_NOTFOUND;
1699 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1700 return MDB_PAGE_NOTFOUND;
1702 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1705 /* For sub-databases, update main root first */
1706 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1708 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1712 txn->mt_dbxs[dbi].md_dirty = 1;
1714 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1715 mpp->mp_parent = NULL;
1717 if ((rc = mdb_touch(txn, mpp)))
1719 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1723 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1727 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1729 MDB_page *omp; /* overflow mpage */
1732 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1733 data->mv_size = leaf->mn_dsize;
1734 data->mv_data = NODEDATA(leaf);
1738 /* Read overflow data.
1740 data->mv_size = leaf->mn_dsize;
1741 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1742 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1743 DPRINTF("read overflow page %lu failed", pgno);
1744 return MDB_PAGE_NOTFOUND;
1746 data->mv_data = omp;
1752 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1753 MDB_val *key, MDB_val *data)
1761 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1763 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1766 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1770 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1773 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1774 if (leaf && exact) {
1775 /* Return first duplicate data item */
1776 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1779 mdb_xcursor_init0(txn, dbi, &mx);
1780 mdb_xcursor_init1(txn, dbi, &mx, leaf);
1781 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1782 if (rc != MDB_SUCCESS)
1784 leaf = NODEPTR(mpp.mp_page, 0);
1786 rc = mdb_read_data(txn, leaf, data);
1795 mdb_sibling(MDB_cursor *cursor, int move_right)
1799 MDB_ppage *parent, *top;
1802 top = CURSOR_TOP(cursor);
1803 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1804 return MDB_NOTFOUND; /* root has no siblings */
1807 DPRINTF("parent page is page %lu, index %u",
1808 parent->mp_page->mp_pgno, parent->mp_ki);
1810 cursor_pop_page(cursor);
1811 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1812 : (parent->mp_ki == 0)) {
1813 DPRINTF("no more keys left, moving to %s sibling",
1814 move_right ? "right" : "left");
1815 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1817 parent = CURSOR_TOP(cursor);
1823 DPRINTF("just moving to %s index key %u",
1824 move_right ? "right" : "left", parent->mp_ki);
1826 assert(IS_BRANCH(parent->mp_page));
1828 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1829 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1830 return MDB_PAGE_NOTFOUND;
1832 mp->parent = parent->mp_page;
1833 mp->parent_index = parent->mp_ki;
1836 cursor_push_page(cursor, mp);
1842 mdb_set_key(MDB_node *node, MDB_val *key)
1847 key->mv_size = node->mn_ksize;
1848 key->mv_data = NODEKEY(node);
1854 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1861 if (cursor->mc_eof) {
1862 return MDB_NOTFOUND;
1865 assert(cursor->mc_initialized);
1867 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1868 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1869 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1870 if (op != MDB_NEXT || rc == MDB_SUCCESS)
1875 top = CURSOR_TOP(cursor);
1878 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1880 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1881 DPRINTF("=====> move to next sibling page");
1882 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1884 return MDB_NOTFOUND;
1886 top = CURSOR_TOP(cursor);
1888 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1892 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1893 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1895 assert(IS_LEAF(mp));
1896 leaf = NODEPTR(mp, top->mp_ki);
1899 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1902 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1903 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1904 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1905 if (rc != MDB_SUCCESS)
1910 return mdb_set_key(leaf, key);
1914 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1921 assert(cursor->mc_initialized);
1923 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1924 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1925 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1926 if (op != MDB_PREV || rc == MDB_SUCCESS)
1931 top = CURSOR_TOP(cursor);
1934 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1936 if (top->mp_ki == 0) {
1937 DPRINTF("=====> move to prev sibling page");
1938 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1939 return MDB_NOTFOUND;
1941 top = CURSOR_TOP(cursor);
1943 top->mp_ki = NUMKEYS(mp) - 1;
1944 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1950 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1951 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1953 assert(IS_LEAF(mp));
1954 leaf = NODEPTR(mp, top->mp_ki);
1957 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1960 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1961 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
1962 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1963 if (rc != MDB_SUCCESS)
1968 return mdb_set_key(leaf, key);
1972 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1973 MDB_cursor_op op, int *exactp)
1982 assert(key->mv_size > 0);
1984 while (CURSOR_TOP(cursor) != NULL)
1985 cursor_pop_page(cursor);
1987 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1988 if (rc != MDB_SUCCESS)
1990 assert(IS_LEAF(mpp.mp_page));
1992 top = CURSOR_TOP(cursor);
1993 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1994 if (exactp != NULL && !*exactp) {
1995 /* MDB_SET specified and not an exact match. */
1996 return MDB_NOTFOUND;
2000 DPRINTF("===> inexact leaf not found, goto sibling");
2001 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2002 return rc; /* no entries matched */
2003 top = CURSOR_TOP(cursor);
2005 mpp.mp_page = top->mp_page;
2006 assert(IS_LEAF(mpp.mp_page));
2007 leaf = NODEPTR(mpp.mp_page, 0);
2010 cursor->mc_initialized = 1;
2014 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2017 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2018 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2019 if (op == MDB_SET || op == MDB_SET_RANGE) {
2020 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2024 if (op == MDB_GET_BOTH) {
2029 op2 = MDB_SET_RANGE;
2031 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
2032 if (rc != MDB_SUCCESS)
2038 rc = mdb_set_key(leaf, key);
2039 if (rc == MDB_SUCCESS) {
2040 DPRINTF("==> cursor placed on key %.*s",
2041 (int)key->mv_size, (char *)key->mv_data);
2049 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2055 while (CURSOR_TOP(cursor) != NULL)
2056 cursor_pop_page(cursor);
2058 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2059 if (rc != MDB_SUCCESS)
2061 assert(IS_LEAF(mpp.mp_page));
2063 leaf = NODEPTR(mpp.mp_page, 0);
2064 cursor->mc_initialized = 1;
2068 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2071 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2072 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2073 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2078 return mdb_set_key(leaf, key);
2082 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2090 while (CURSOR_TOP(cursor) != NULL)
2091 cursor_pop_page(cursor);
2093 lkey.mv_size = MAXKEYSIZE+1;
2094 lkey.mv_data = NULL;
2096 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2097 if (rc != MDB_SUCCESS)
2099 assert(IS_LEAF(mpp.mp_page));
2101 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2102 cursor->mc_initialized = 1;
2105 top = CURSOR_TOP(cursor);
2106 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2109 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2112 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2113 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, leaf);
2114 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2120 return mdb_set_key(leaf, key);
2124 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2134 case MDB_GET_BOTH_RANGE:
2142 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2144 } else if (op != MDB_SET_RANGE)
2145 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2147 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2151 case MDB_NEXT_NODUP:
2152 if (!cursor->mc_initialized)
2153 rc = mdb_cursor_first(cursor, key, data);
2155 rc = mdb_cursor_next(cursor, key, data, op);
2159 case MDB_PREV_NODUP:
2160 if (!cursor->mc_initialized || cursor->mc_eof)
2161 rc = mdb_cursor_last(cursor, key, data);
2163 rc = mdb_cursor_prev(cursor, key, data, op);
2166 rc = mdb_cursor_first(cursor, key, data);
2169 rc = mdb_cursor_last(cursor, key, data);
2172 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2180 /* Allocate a page and initialize it
2183 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2187 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2189 DPRINTF("allocated new mpage %lu, page size %u",
2190 dp->p.mp_pgno, txn->mt_env->me_psize);
2191 dp->p.mp_flags = flags | P_DIRTY;
2192 dp->p.mp_lower = PAGEHDRSZ;
2193 dp->p.mp_upper = txn->mt_env->me_psize;
2195 if (IS_BRANCH(&dp->p))
2196 txn->mt_dbs[dbi].md_branch_pages++;
2197 else if (IS_LEAF(&dp->p))
2198 txn->mt_dbs[dbi].md_leaf_pages++;
2199 else if (IS_OVERFLOW(&dp->p)) {
2200 txn->mt_dbs[dbi].md_overflow_pages += num;
2201 dp->p.mp_pages = num;
2208 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2212 sz = LEAFSIZE(key, data);
2213 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2214 /* put on overflow page */
2215 sz -= data->mv_size - sizeof(pgno_t);
2218 return sz + sizeof(indx_t);
2222 mdb_branch_size(MDB_env *env, MDB_val *key)
2227 if (sz >= env->me_psize / MDB_MINKEYS) {
2228 /* put on overflow page */
2229 /* not implemented */
2230 /* sz -= key->size - sizeof(pgno_t); */
2233 return sz + sizeof(indx_t);
2237 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2238 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2241 size_t node_size = NODESIZE;
2244 MDB_dpage *ofp = NULL; /* overflow page */
2246 assert(mp->mp_upper >= mp->mp_lower);
2248 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2249 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2250 IS_LEAF(mp) ? "leaf" : "branch",
2251 mp->mp_pgno, indx, key ? key->mv_size : 0);
2254 node_size += key->mv_size;
2258 if (F_ISSET(flags, F_BIGDATA)) {
2259 /* Data already on overflow page. */
2260 node_size += sizeof(pgno_t);
2261 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2262 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2263 /* Put data on overflow page. */
2264 DPRINTF("data size is %zu, put on overflow page",
2266 node_size += sizeof(pgno_t);
2267 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2269 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2272 node_size += data->mv_size;
2276 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2277 DPRINTF("not enough room in page %lu, got %u ptrs",
2278 mp->mp_pgno, NUMKEYS(mp));
2279 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2280 mp->mp_upper - mp->mp_lower);
2281 DPRINTF("node size = %zu", node_size);
2285 /* Move higher pointers up one slot. */
2286 for (i = NUMKEYS(mp); i > indx; i--)
2287 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2289 /* Adjust free space offsets. */
2290 ofs = mp->mp_upper - node_size;
2291 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2292 mp->mp_ptrs[indx] = ofs;
2294 mp->mp_lower += sizeof(indx_t);
2296 /* Write the node data. */
2297 node = NODEPTR(mp, indx);
2298 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2299 node->mn_flags = flags;
2301 node->mn_dsize = data->mv_size;
2303 node->mn_pgno = pgno;
2306 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2311 if (F_ISSET(flags, F_BIGDATA))
2312 memcpy(node->mn_data + key->mv_size, data->mv_data,
2315 memcpy(node->mn_data + key->mv_size, data->mv_data,
2318 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2320 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2328 mdb_del_node(MDB_page *mp, indx_t indx)
2331 indx_t i, j, numkeys, ptr;
2335 DPRINTF("delete node %u on %s page %lu", indx,
2336 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2337 assert(indx < NUMKEYS(mp));
2339 node = NODEPTR(mp, indx);
2340 sz = NODESIZE + node->mn_ksize;
2342 if (F_ISSET(node->mn_flags, F_BIGDATA))
2343 sz += sizeof(pgno_t);
2345 sz += NODEDSZ(node);
2348 ptr = mp->mp_ptrs[indx];
2349 numkeys = NUMKEYS(mp);
2350 for (i = j = 0; i < numkeys; i++) {
2352 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2353 if (mp->mp_ptrs[i] < ptr)
2354 mp->mp_ptrs[j] += sz;
2359 base = (char *)mp + mp->mp_upper;
2360 memmove(base + sz, base, ptr - mp->mp_upper);
2362 mp->mp_lower -= sizeof(indx_t);
2367 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2372 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2373 mx->mx_txn.mt_dbs = mx->mx_dbs;
2374 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2375 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2377 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2382 mx->mx_dbxs[dbn+1].md_parent = dbn;
2383 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2384 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2385 mx->mx_dbxs[dbn+1].md_dirty = 0;
2386 mx->mx_txn.mt_numdbs = dbn+2;
2388 SLIST_INIT(&mx->mx_cursor.mc_stack);
2389 mx->mx_cursor.mc_txn = &mx->mx_txn;
2390 mx->mx_cursor.mc_dbi = dbn+1;
2394 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_node *node)
2396 MDB_db *db = NODEDATA(node);
2398 mx->mx_dbs[0] = txn->mt_dbs[0];
2399 mx->mx_dbs[1] = txn->mt_dbs[1];
2401 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2406 mx->mx_dbs[dbn] = *db;
2407 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2408 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2409 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2410 mx->mx_txn.mt_oldest = txn->mt_oldest;
2411 mx->mx_txn.mt_u = txn->mt_u;
2415 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2417 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2418 txn->mt_oldest = mx->mx_txn.mt_oldest;
2419 txn->mt_u = mx->mx_txn.mt_u;
2420 txn->mt_dbs[0] = mx->mx_dbs[0];
2421 txn->mt_dbs[1] = mx->mx_dbs[1];
2422 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2423 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2425 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2426 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2431 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2434 size_t size = sizeof(MDB_cursor);
2436 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2439 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2440 size += sizeof(MDB_xcursor);
2442 if ((cursor = calloc(1, size)) != NULL) {
2443 SLIST_INIT(&cursor->mc_stack);
2444 cursor->mc_dbi = dbi;
2445 cursor->mc_txn = txn;
2446 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2447 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2448 cursor->mc_xcursor = mx;
2449 mdb_xcursor_init0(txn, dbi, mx);
2460 /* Return the count of duplicate data items for the current key */
2462 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2464 if (mc == NULL || countp == NULL)
2467 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2470 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2473 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2478 mdb_cursor_close(MDB_cursor *cursor)
2480 if (cursor != NULL) {
2481 while(!CURSOR_EMPTY(cursor))
2482 cursor_pop_page(cursor);
2483 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2484 mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2485 while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2486 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2494 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2496 indx_t ptr, i, numkeys;
2502 node = NODEPTR(mp, indx);
2503 ptr = mp->mp_ptrs[indx];
2504 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2506 (int)node->mn_ksize, (char *)NODEKEY(node),
2507 (int)key->mv_size, (char *)key->mv_data,
2510 delta = key->mv_size - node->mn_ksize;
2512 if (delta > 0 && SIZELEFT(mp) < delta) {
2513 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2517 numkeys = NUMKEYS(mp);
2518 for (i = 0; i < numkeys; i++) {
2519 if (mp->mp_ptrs[i] <= ptr)
2520 mp->mp_ptrs[i] -= delta;
2523 base = (char *)mp + mp->mp_upper;
2524 len = ptr - mp->mp_upper + NODESIZE;
2525 memmove(base - delta, base, len);
2526 mp->mp_upper -= delta;
2528 node = NODEPTR(mp, indx);
2529 node->mn_ksize = key->mv_size;
2532 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2537 /* Move a node from src to dst.
2540 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2541 MDB_pageparent *dst, indx_t dstindx)
2547 srcnode = NODEPTR(src->mp_page, srcindx);
2548 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2549 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2551 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2552 src->mp_page->mp_pgno,
2553 dstindx, dst->mp_page->mp_pgno);
2555 /* Mark src and dst as dirty. */
2556 if ((rc = mdb_touch(txn, src)) ||
2557 (rc = mdb_touch(txn, dst)))
2560 /* Add the node to the destination page.
2562 key.mv_size = srcnode->mn_ksize;
2563 key.mv_data = NODEKEY(srcnode);
2564 data.mv_size = NODEDSZ(srcnode);
2565 data.mv_data = NODEDATA(srcnode);
2566 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2568 if (rc != MDB_SUCCESS)
2571 /* Delete the node from the source page.
2573 mdb_del_node(src->mp_page, srcindx);
2575 /* Update the parent separators.
2577 if (srcindx == 0 && src->mp_pi != 0) {
2578 DPRINTF("update separator for source page %lu to [%.*s]",
2579 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2580 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2581 &key)) != MDB_SUCCESS)
2585 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2587 nullkey.mv_size = 0;
2588 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2591 if (dstindx == 0 && dst->mp_pi != 0) {
2592 DPRINTF("update separator for destination page %lu to [%.*s]",
2593 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2594 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2595 &key)) != MDB_SUCCESS)
2599 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2601 nullkey.mv_size = 0;
2602 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2609 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2618 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2620 assert(txn != NULL);
2621 assert(src->mp_parent); /* can't merge root page */
2622 assert(dst->mp_parent);
2624 /* Mark src and dst as dirty. */
2625 if ((rc = mdb_touch(txn, src)) ||
2626 (rc = mdb_touch(txn, dst)))
2629 /* Move all nodes from src to dst.
2631 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2632 srcnode = NODEPTR(src->mp_page, i);
2634 key.mv_size = srcnode->mn_ksize;
2635 key.mv_data = NODEKEY(srcnode);
2636 data.mv_size = NODEDSZ(srcnode);
2637 data.mv_data = NODEDATA(srcnode);
2638 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2639 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2640 if (rc != MDB_SUCCESS)
2644 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2645 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2647 /* Unlink the src page from parent.
2649 mdb_del_node(src->mp_parent, src->mp_pi);
2650 if (src->mp_pi == 0) {
2652 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2656 if (IS_LEAF(src->mp_page))
2657 txn->mt_dbs[dbi].md_leaf_pages--;
2659 txn->mt_dbs[dbi].md_branch_pages--;
2661 mpp.mp_page = src->mp_parent;
2662 dh = (MDB_dhead *)src->mp_parent;
2664 mpp.mp_parent = dh->md_parent;
2665 mpp.mp_pi = dh->md_pi;
2667 return mdb_rebalance(txn, dbi, &mpp);
2670 #define FILL_THRESHOLD 250
2673 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2678 indx_t si = 0, di = 0;
2680 assert(txn != NULL);
2681 assert(mpp != NULL);
2683 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2684 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2685 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2687 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2688 DPRINTF("no need to rebalance page %lu, above fill threshold",
2689 mpp->mp_page->mp_pgno);
2693 if (mpp->mp_parent == NULL) {
2694 if (NUMKEYS(mpp->mp_page) == 0) {
2695 DPRINTF("tree is completely empty");
2696 txn->mt_dbs[dbi].md_root = P_INVALID;
2697 txn->mt_dbs[dbi].md_depth--;
2698 txn->mt_dbs[dbi].md_leaf_pages--;
2699 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2700 DPRINTF("collapsing root page!");
2701 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2702 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2703 return MDB_PAGE_NOTFOUND;
2704 txn->mt_dbs[dbi].md_depth--;
2705 txn->mt_dbs[dbi].md_branch_pages--;
2707 DPRINTF("root page doesn't need rebalancing");
2711 /* The parent (branch page) must have at least 2 pointers,
2712 * otherwise the tree is invalid.
2714 assert(NUMKEYS(mpp->mp_parent) > 1);
2716 /* Leaf page fill factor is below the threshold.
2717 * Try to move keys from left or right neighbor, or
2718 * merge with a neighbor page.
2723 if (mpp->mp_pi == 0) {
2724 /* We're the leftmost leaf in our parent.
2726 DPRINTF("reading right neighbor");
2727 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2728 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2729 return MDB_PAGE_NOTFOUND;
2730 npp.mp_pi = mpp->mp_pi + 1;
2732 di = NUMKEYS(mpp->mp_page);
2734 /* There is at least one neighbor to the left.
2736 DPRINTF("reading left neighbor");
2737 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2738 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2739 return MDB_PAGE_NOTFOUND;
2740 npp.mp_pi = mpp->mp_pi - 1;
2741 si = NUMKEYS(npp.mp_page) - 1;
2744 npp.mp_parent = mpp->mp_parent;
2746 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2747 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2749 /* If the neighbor page is above threshold and has at least two
2750 * keys, move one key from it.
2752 * Otherwise we should try to merge them.
2754 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2755 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2756 else { /* FIXME: if (has_enough_room()) */
2757 if (mpp->mp_pi == 0)
2758 return mdb_merge(txn, dbi, &npp, mpp);
2760 return mdb_merge(txn, dbi, mpp, &npp);
2765 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2769 /* add overflow pages to free list */
2770 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2774 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2775 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2776 for (i=0; i<ovpages; i++) {
2777 DPRINTF("freed ov page %lu", pg);
2778 mdb_midl_insert(txn->mt_free_pgs, pg);
2782 mdb_del_node(mpp->mp_page, ki);
2783 txn->mt_dbs[dbi].md_entries--;
2784 rc = mdb_rebalance(txn, dbi, mpp);
2785 if (rc != MDB_SUCCESS)
2786 txn->mt_flags |= MDB_TXN_ERROR;
2792 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2793 MDB_val *key, MDB_val *data,
2801 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2803 assert(key != NULL);
2805 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2808 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2812 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2816 mpp.mp_parent = NULL;
2818 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2821 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2822 if (leaf == NULL || !exact) {
2823 return MDB_NOTFOUND;
2826 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2830 mdb_xcursor_init0(txn, dbi, &mx);
2831 mdb_xcursor_init1(txn, dbi, &mx, leaf);
2832 if (flags == MDB_DEL_DUP) {
2833 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2834 mdb_xcursor_fini(txn, dbi, &mx);
2835 if (rc != MDB_SUCCESS)
2837 /* If sub-DB still has entries, we're done */
2838 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2839 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2843 /* otherwise fall thru and delete the sub-DB */
2845 /* add all the child DB's pages to the free list */
2846 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2847 NULL, &mx.mx_cursor, 0, &mp2);
2848 if (rc == MDB_SUCCESS) {
2849 MDB_ppage *top, *parent;
2853 cursor_pop_page(&mx.mx_cursor);
2854 top = CURSOR_TOP(&mx.mx_cursor);
2856 parent = SLIST_NEXT(top, mp_entry);
2857 while (parent != NULL) {
2858 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2859 ni = NODEPTR(top->mp_page, i);
2860 mdb_midl_insert(txn->mt_free_pgs, ni->mn_pgno);
2864 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2865 cursor_pop_page(&mx.mx_cursor);
2866 top = CURSOR_TOP(&mx.mx_cursor);
2867 parent = SLIST_NEXT(top, mp_entry);
2869 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2870 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2875 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2880 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2883 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2886 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2887 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2888 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2889 * refer to a node in the new right sibling page.
2892 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2893 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2896 int rc = MDB_SUCCESS, ins_new = 0;
2899 unsigned int i, j, split_indx;
2901 MDB_val sepkey, rkey, rdata;
2903 MDB_dpage *mdp, *rdp, *pdp;
2906 assert(txn != NULL);
2908 dh = ((MDB_dhead *)*mpp) - 1;
2909 mdp = (MDB_dpage *)dh;
2910 newindx = *newindxp;
2912 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2913 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2914 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2916 if (mdp->h.md_parent == NULL) {
2917 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2920 mdp->h.md_parent = &pdp->p;
2921 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2922 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2923 txn->mt_dbs[dbi].md_depth++;
2925 /* Add left (implicit) pointer. */
2926 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2927 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
2930 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2933 /* Create a right sibling. */
2934 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2936 rdp->h.md_parent = mdp->h.md_parent;
2937 rdp->h.md_pi = mdp->h.md_pi + 1;
2938 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2940 /* Move half of the keys to the right sibling. */
2941 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2943 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2944 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2945 mdp->p.mp_lower = PAGEHDRSZ;
2946 mdp->p.mp_upper = txn->mt_env->me_psize;
2948 split_indx = NUMKEYS(copy) / 2 + 1;
2950 /* First find the separating key between the split pages.
2952 memset(&sepkey, 0, sizeof(sepkey));
2953 if (newindx == split_indx) {
2954 sepkey.mv_size = newkey->mv_size;
2955 sepkey.mv_data = newkey->mv_data;
2957 node = NODEPTR(copy, split_indx);
2958 sepkey.mv_size = node->mn_ksize;
2959 sepkey.mv_data = NODEKEY(node);
2962 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2964 /* Copy separator key to the parent.
2966 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2967 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2968 &sepkey, NULL, rdp->p.mp_pgno);
2970 /* Right page might now have changed parent.
2971 * Check if left page also changed parent.
2973 if (rdp->h.md_parent != mdp->h.md_parent &&
2974 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2975 mdp->h.md_parent = rdp->h.md_parent;
2976 mdp->h.md_pi = rdp->h.md_pi - 1;
2979 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2980 &sepkey, NULL, rdp->p.mp_pgno, 0);
2982 if (rc != MDB_SUCCESS) {
2987 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2988 if (i < split_indx) {
2989 /* Re-insert in left sibling. */
2992 /* Insert in right sibling. */
2993 if (i == split_indx)
2994 /* Reset insert index for right sibling. */
2995 j = (i == newindx && ins_new);
2999 if (i == newindx && !ins_new) {
3000 /* Insert the original entry that caused the split. */
3001 rkey.mv_data = newkey->mv_data;
3002 rkey.mv_size = newkey->mv_size;
3003 if (IS_LEAF(&mdp->p)) {
3004 rdata.mv_data = newdata->mv_data;
3005 rdata.mv_size = newdata->mv_size;
3012 /* Update page and index for the new key. */
3015 } else if (i == NUMKEYS(copy)) {
3018 node = NODEPTR(copy, i);
3019 rkey.mv_data = NODEKEY(node);
3020 rkey.mv_size = node->mn_ksize;
3021 if (IS_LEAF(&mdp->p)) {
3022 rdata.mv_data = NODEDATA(node);
3023 rdata.mv_size = node->mn_dsize;
3025 pgno = node->mn_pgno;
3026 flags = node->mn_flags;
3031 if (!IS_LEAF(&mdp->p) && j == 0) {
3032 /* First branch index doesn't need key data. */
3036 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
3044 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3045 MDB_val *key, MDB_val *data, unsigned int flags)
3047 int rc = MDB_SUCCESS, exact;
3051 MDB_val xdata, *rdata;
3054 DPRINTF("==> put key %.*s, size %zu, data size %zu",
3055 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
3057 mpp.mp_parent = NULL;
3059 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3060 if (rc == MDB_SUCCESS) {
3061 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3062 if (leaf && exact) {
3063 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3066 if (flags == MDB_NOOVERWRITE) {
3067 DPRINTF("duplicate key %.*s",
3068 (int)key->mv_size, (char *)key->mv_data);
3069 return MDB_KEYEXIST;
3071 /* same size, just replace it */
3072 if (NODEDSZ(leaf) == data->mv_size) {
3073 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3076 mdb_del_node(mpp.mp_page, ki);
3078 if (leaf == NULL) { /* append if not found */
3079 ki = NUMKEYS(mpp.mp_page);
3080 DPRINTF("appending key at index %i", ki);
3082 } else if (rc == MDB_NOTFOUND) {
3084 /* new file, just write a root leaf page */
3085 DPRINTF("allocating new root leaf page");
3086 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3089 mpp.mp_page = &dp->p;
3090 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3091 txn->mt_dbs[dbi].md_depth++;
3097 assert(IS_LEAF(mpp.mp_page));
3098 DPRINTF("there are %u keys, should insert new key at index %i",
3099 NUMKEYS(mpp.mp_page), ki);
3101 /* For sorted dups, the data item at this level is a DB record
3102 * for a child DB; the actual data elements are stored as keys
3105 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3107 xdata.mv_size = sizeof(MDB_db);
3108 xdata.mv_data = &dummy;
3109 memset(&dummy, 0, sizeof(dummy));
3110 dummy.md_root = P_INVALID;
3115 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, rdata)) {
3116 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3118 /* There is room already in this leaf page. */
3119 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3122 if (rc != MDB_SUCCESS)
3123 txn->mt_flags |= MDB_TXN_ERROR;
3125 txn->mt_dbs[dbi].md_entries++;
3127 /* Remember if we just added a subdatabase */
3128 if (flags & F_SUBDATA) {
3129 leaf = NODEPTR(mpp.mp_page, ki);
3130 leaf->mn_flags |= F_SUBDATA;
3133 /* Now store the actual data in the child DB. Note that we're
3134 * storing the user data in the keys field, so there are strict
3135 * size limits on dupdata. The actual data fields of the child
3136 * DB are all zero size.
3138 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3141 leaf = NODEPTR(mpp.mp_page, ki);
3143 mdb_xcursor_init0(txn, dbi, &mx);
3144 mdb_xcursor_init1(txn, dbi, &mx, leaf);
3147 if (flags == MDB_NODUPDATA)
3148 flags = MDB_NOOVERWRITE;
3149 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3150 mdb_xcursor_fini(txn, dbi, &mx);
3151 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3161 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3162 MDB_val *key, MDB_val *data, unsigned int flags)
3164 assert(key != NULL);
3165 assert(data != NULL);
3167 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3170 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3174 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3178 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3181 return mdb_put0(txn, dbi, key, data, flags);
3185 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3187 #define CHANGEABLE (MDB_NOSYNC)
3188 if ((flag & CHANGEABLE) != flag)
3191 env->me_flags |= flag;
3193 env->me_flags &= ~flag;
3198 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3203 *arg = env->me_flags;
3208 mdb_env_get_path(MDB_env *env, const char **arg)
3213 *arg = env->me_path;
3218 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3220 arg->ms_psize = env->me_psize;
3221 arg->ms_depth = db->md_depth;
3222 arg->ms_branch_pages = db->md_branch_pages;
3223 arg->ms_leaf_pages = db->md_leaf_pages;
3224 arg->ms_overflow_pages = db->md_overflow_pages;
3225 arg->ms_entries = db->md_entries;
3230 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3232 if (env == NULL || arg == NULL)
3235 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3238 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3248 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3249 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3253 /* Is the DB already open? */
3255 for (i=2; i<txn->mt_numdbs; i++) {
3256 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3257 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3263 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3266 /* Find the DB info */
3268 key.mv_data = (void *)name;
3269 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3271 /* Create if requested */
3272 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3274 data.mv_size = sizeof(MDB_db);
3275 data.mv_data = &dummy;
3276 memset(&dummy, 0, sizeof(dummy));
3277 dummy.md_root = P_INVALID;
3278 dummy.md_flags = flags & 0xffff;
3279 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3283 /* OK, got info, add to table */
3284 if (rc == MDB_SUCCESS) {
3285 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3286 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3287 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3288 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3289 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3290 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3291 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3292 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3293 *dbi = txn->mt_numdbs;
3300 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3302 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3305 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3308 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3311 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3313 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3314 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3315 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3319 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3321 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3324 txn->mt_dbxs[dbi].md_cmp = cmp;
3328 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3330 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3333 txn->mt_dbxs[dbi].md_dcmp = cmp;
3337 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3339 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3342 txn->mt_dbxs[dbi].md_rel = rel;