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
57 #define ULONG unsigned long
66 #if DEBUG && defined(__GNUC__)
67 # define DPRINTF(fmt, ...) \
68 fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
70 # define DPRINTF(...) ((void) 0)
75 #define MDB_MAGIC 0xBEEFC0DE
77 #define MAXKEYSIZE 255
79 #define P_INVALID (~0UL)
81 #define F_ISSET(w, f) (((w) & (f)) == (f))
83 typedef uint16_t indx_t;
85 #define DEFAULT_READERS 126
86 #define DEFAULT_MAPSIZE 1048576
88 /* Lock descriptor stuff */
93 typedef struct MDB_rxbody {
98 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
101 typedef struct MDB_reader {
103 /* cache line alignment */
104 char pad[CACHELINE-sizeof(MDB_rxbody)];
109 uint32_t mt_version; \
110 pthread_mutex_t mt_mutex; \
112 uint32_t mt_numreaders
113 typedef struct MDB_txbody {
117 typedef struct MDB_txninfo {
119 char pad[CACHELINE-sizeof(MDB_txbody)];
120 pthread_mutex_t mt_wmutex;
121 char pad2[CACHELINE-sizeof(pthread_mutex_t)];
122 MDB_reader mt_readers[1];
125 /* Common header for all page types. Overflow pages
126 * occupy a number of contiguous pages with no
127 * headers on any page after the first.
129 typedef struct MDB_page { /* represents a page of storage */
130 #define mp_pgno mp_p.p_pgno
132 pgno_t p_pgno; /* page number */
135 #define P_BRANCH 0x01 /* branch page */
136 #define P_LEAF 0x02 /* leaf page */
137 #define P_OVERFLOW 0x04 /* overflow page */
138 #define P_META 0x08 /* meta page */
139 #define P_DIRTY 0x10 /* dirty page */
141 #define mp_lower mp_pb.pb.pb_lower
142 #define mp_upper mp_pb.pb.pb_upper
143 #define mp_pages mp_pb.pb_pages
146 indx_t pb_lower; /* lower bound of free space */
147 indx_t pb_upper; /* upper bound of free space */
149 uint32_t pb_pages; /* number of overflow pages */
151 indx_t mp_ptrs[1]; /* dynamic size */
154 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
156 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
157 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
158 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
159 ((env)->me_psize - PAGEHDRSZ))
160 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
161 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
162 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
164 #define OVPAGES(size, psize) (PAGEHDRSZ + size + psize - 1) / psize;
166 typedef struct MDB_db {
170 ULONG md_branch_pages;
172 ULONG md_overflow_pages;
180 typedef struct MDB_meta { /* meta (footer) page content */
183 void *mm_address; /* address for fixed mapping */
184 size_t mm_mapsize; /* size of mmap region */
185 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
186 #define mm_psize mm_dbs[0].md_pad
187 #define mm_flags mm_dbs[0].md_flags
188 pgno_t mm_last_pg; /* last used page in file */
189 ULONG mm_txnid; /* txnid that committed this page */
192 typedef struct MDB_dhead { /* a dirty page */
193 STAILQ_ENTRY(MDB_dpage) md_next; /* queue of dirty pages */
195 unsigned md_pi; /* parent index */
199 typedef struct MDB_dpage {
204 STAILQ_HEAD(dirty_queue, MDB_dpage); /* FIXME: use a sorted data structure */
206 typedef struct MDB_oldpages {
207 struct MDB_oldpages *mo_next;
209 pgno_t mo_pages[1]; /* dynamic */
212 typedef struct MDB_pageparent {
218 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
219 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
221 typedef struct MDB_ppage { /* ordered list of pages */
222 SLIST_ENTRY(MDB_ppage) mp_entry;
224 unsigned int mp_ki; /* cursor index on page */
226 SLIST_HEAD(page_stack, MDB_ppage);
228 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
229 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
230 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
231 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
235 struct page_stack mc_stack; /* stack of parent pages */
237 short mc_initialized; /* 1 if initialized */
238 short mc_eof; /* 1 if end is reached */
241 #define METAHASHLEN offsetof(MDB_meta, mm_hash)
242 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
244 typedef struct MDB_node {
245 #define mn_pgno mn_p.np_pgno
246 #define mn_dsize mn_p.np_dsize
248 pgno_t np_pgno; /* child page number */
249 uint32_t np_dsize; /* leaf data size */
251 unsigned int mn_flags:4;
252 unsigned int mn_ksize:12; /* key size */
253 #define F_BIGDATA 0x01 /* data put on overflow page */
258 typedef struct MDB_dbx {
260 MDB_cmp_func *md_cmp; /* user compare function */
261 MDB_cmp_func *md_dcmp; /* user dupsort function */
262 MDB_rel_func *md_rel; /* user relocate function */
266 pgno_t mt_next_pgno; /* next unallocated page */
270 pgno_t *mt_free_pgs; /* this is an IDL */
272 struct dirty_queue *dirty_queue; /* modified pages */
275 MDB_dbx *mt_dbxs; /* array */
277 unsigned int mt_numdbs;
279 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
280 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
281 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
282 unsigned int mt_flags;
289 unsigned int me_maxreaders;
290 unsigned int me_numdbs;
291 unsigned int me_maxdbs;
294 MDB_txninfo *me_txns;
295 MDB_meta *me_metas[2];
297 MDB_txn *me_txn; /* current write transaction */
299 off_t me_size; /* current file size */
300 unsigned int me_psize;
302 MDB_dbx *me_dbxs; /* array */
304 MDB_oldpages *me_pghead;
305 pthread_key_t me_txkey; /* thread-key for readers */
308 #define NODESIZE offsetof(MDB_node, mn_data)
310 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
311 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
312 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
313 #define NODEKEY(node) (void *)((node)->mn_data)
314 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
315 #define NODEPGNO(node) ((node)->mn_pgno)
316 #define NODEDSZ(node) ((node)->mn_dsize)
318 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
319 #define MDB_MAXCACHE_DEF 1024 /* max number of pages to keep in cache */
321 static int mdb_search_page_root(MDB_txn *txn,
322 MDB_dbi dbi, MDB_val *key,
323 MDB_cursor *cursor, int modify,
324 MDB_pageparent *mpp);
325 static int mdb_search_page(MDB_txn *txn,
326 MDB_dbi dbi, MDB_val *key,
327 MDB_cursor *cursor, int modify,
328 MDB_pageparent *mpp);
330 static int mdbenv_read_header(MDB_env *env, MDB_meta *meta);
331 static int mdbenv_read_meta(MDB_env *env, int *which);
332 static int mdbenv_write_meta(MDB_txn *txn);
333 static MDB_page *mdbenv_get_page(MDB_env *env, pgno_t pgno);
335 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
336 MDB_val *key, int *exactp, unsigned int *kip);
337 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
338 indx_t indx, MDB_val *key, MDB_val *data,
339 pgno_t pgno, uint8_t flags);
340 static void mdb_del_node(MDB_page *mp, indx_t indx);
341 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
342 MDB_pageparent *mpp, MDB_node *leaf);
343 static int mdb_read_data(MDB_env *env, MDB_node *leaf, MDB_val *data);
345 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
346 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
347 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
348 MDB_pageparent *src, indx_t srcindx,
349 MDB_pageparent *dst, indx_t dstindx);
350 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
351 MDB_pageparent *dst);
352 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
353 unsigned int *newindxp, MDB_val *newkey,
354 MDB_val *newdata, pgno_t newpgno);
355 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
357 static void cursor_pop_page(MDB_cursor *cursor);
358 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
361 static int mdb_set_key(MDB_node *node, MDB_val *key);
362 static int mdb_sibling(MDB_cursor *cursor, int move_right);
363 static int mdb_cursor_next(MDB_cursor *cursor,
364 MDB_val *key, MDB_val *data);
365 static int mdb_cursor_prev(MDB_cursor *cursor,
366 MDB_val *key, MDB_val *data);
367 static int mdb_cursor_set(MDB_cursor *cursor,
368 MDB_val *key, MDB_val *data, int *exactp);
369 static int mdb_cursor_first(MDB_cursor *cursor,
370 MDB_val *key, MDB_val *data);
371 static int mdb_cursor_last(MDB_cursor *cursor,
372 MDB_val *key, MDB_val *data);
374 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
376 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
378 static int memncmp(const void *s1, size_t n1,
379 const void *s2, size_t n2);
380 static int memnrcmp(const void *s1, size_t n1,
381 const void *s2, size_t n2);
384 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
386 int diff, len_diff = -1;
389 len_diff = (n1 > n2);
392 diff = memcmp(s1, s2, n1);
393 return diff ? diff : len_diff;
397 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
399 const unsigned char *p1, *p2, *p1_lim;
406 p1 = (const unsigned char *)s1 + n1 - 1;
407 p2 = (const unsigned char *)s2 + n2 - 1;
409 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
411 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
417 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
419 return txn->mt_dbxs[dbi].md_cmp(a, b);
423 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
425 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_REVERSEKEY))
426 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
428 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
431 /* Allocate new page(s) for writing */
433 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
436 pgno_t pgno = P_INVALID;
437 ULONG oldest = txn->mt_txnid - 2;
439 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
440 /* See if there's anything in the free DB */
445 mpp.mp_parent = NULL;
447 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
448 leaf = NODEPTR(mpp.mp_page, 0);
449 kptr = (ULONG *)NODEKEY(leaf);
451 /* It's potentially usable, unless there are still
452 * older readers outstanding. Grab it.
454 if (oldest > *kptr) {
459 mdb_read_data(txn->mt_env, leaf, &data);
460 idl = (ULONG *)data.mv_data;
461 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
462 mop->mo_next = txn->mt_env->me_pghead;
463 mop->mo_txnid = *kptr;
464 txn->mt_env->me_pghead = mop;
465 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
470 DPRINTF("IDL read txn %lu root %lu num %lu",
471 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
472 for (i=0; i<idl[0]; i++) {
473 DPRINTF("IDL %lu", idl[i+1]);
477 /* drop this IDL from the DB */
478 mpp.mp_parent = NULL;
480 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
481 leaf = NODEPTR(mpp.mp_page, 0);
482 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
485 if (txn->mt_env->me_pghead) {
487 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
488 ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
491 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
493 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
494 MDB_oldpages *mop = txn->mt_env->me_pghead;
495 txn->mt_oldest = oldest;
497 /* FIXME: For now, always use fresh pages. We
498 * really ought to search the free list for a
503 /* peel pages off tail, so we only have to truncate the list */
504 pgno = MDB_IDL_LAST(mop->mo_pages);
505 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
507 if (mop->mo_pages[2] > mop->mo_pages[1])
508 mop->mo_pages[0] = 0;
512 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
513 txn->mt_env->me_pghead = mop->mo_next;
520 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
523 dp->h.md_parent = parent;
524 dp->h.md_pi = parent_idx;
525 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
526 if (pgno == P_INVALID) {
527 dp->p.mp_pgno = txn->mt_next_pgno;
528 txn->mt_next_pgno += num;
530 dp->p.mp_pgno = pgno;
536 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
539 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
541 MDB_page *mp = pp->mp_page;
546 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
548 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
550 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
551 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
552 pgno = dp->p.mp_pgno;
553 memcpy(&dp->p, mp, txn->mt_env->me_psize);
556 mp->mp_flags |= P_DIRTY;
558 /* Update the page number to new touched page. */
559 if (pp->mp_parent != NULL)
560 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
567 mdbenv_sync(MDB_env *env)
570 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
571 if (fsync(env->me_fd))
578 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
583 if ((txn = calloc(1, sizeof(*txn))) == NULL) {
584 DPRINTF("calloc: %s", strerror(errno));
589 txn->mt_flags |= MDB_TXN_RDONLY;
591 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
592 if (txn->mt_u.dirty_queue == NULL) {
596 STAILQ_INIT(txn->mt_u.dirty_queue);
598 pthread_mutex_lock(&env->me_txns->mt_wmutex);
599 env->me_txns->mt_txnid++;
600 txn->mt_free_pgs = malloc(MDB_IDL_UM_SIZEOF);
601 if (txn->mt_free_pgs == NULL) {
602 free(txn->mt_u.dirty_queue);
606 txn->mt_free_pgs[0] = 0;
609 txn->mt_txnid = env->me_txns->mt_txnid;
611 MDB_reader *r = pthread_getspecific(env->me_txkey);
614 pthread_mutex_lock(&env->me_txns->mt_mutex);
615 for (i=0; i<env->me_maxreaders; i++) {
616 if (env->me_txns->mt_readers[i].mr_pid == 0) {
617 env->me_txns->mt_readers[i].mr_pid = getpid();
618 env->me_txns->mt_readers[i].mr_tid = pthread_self();
619 r = &env->me_txns->mt_readers[i];
620 pthread_setspecific(env->me_txkey, r);
621 if (i >= env->me_txns->mt_numreaders)
622 env->me_txns->mt_numreaders = i+1;
626 pthread_mutex_unlock(&env->me_txns->mt_mutex);
627 if (i == env->me_maxreaders) {
631 r->mr_txnid = txn->mt_txnid;
632 txn->mt_u.reader = r;
639 if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
644 /* Copy the DB arrays */
645 txn->mt_numdbs = env->me_numdbs;
646 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
647 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
648 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
649 if (txn->mt_numdbs > 2)
650 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
651 (txn->mt_numdbs - 2) * sizeof(MDB_db));
655 txn->mt_flags |= MDB_TXN_METOGGLE;
656 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
659 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
660 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
667 mdb_txn_abort(MDB_txn *txn)
676 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
677 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
681 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
682 txn->mt_u.reader->mr_txnid = 0;
685 /* Discard all dirty pages. */
686 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
687 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
688 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
691 free(txn->mt_free_pgs);
692 free(txn->mt_u.dirty_queue);
694 while ((mop = txn->mt_env->me_pghead)) {
695 txn->mt_env->me_pghead = mop->mo_next;
700 env->me_txns->mt_txnid--;
701 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
708 mdb_txn_commit(MDB_txn *txn)
717 struct iovec iov[MDB_COMMIT_PAGES];
720 assert(txn->mt_env != NULL);
724 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
725 DPRINTF("attempt to commit read-only transaction");
730 if (txn != env->me_txn) {
731 DPRINTF("attempt to commit unknown transaction");
736 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
737 DPRINTF("error flag is set, can't commit");
742 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
745 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
746 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
748 /* should only be one record now */
749 if (env->me_pghead) {
753 mop = env->me_pghead;
754 key.mv_size = sizeof(pgno_t);
755 key.mv_data = (char *)&mop->mo_txnid;
756 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
757 data.mv_data = mop->mo_pages;
758 mdb_put(txn, FREE_DBI, &key, &data, 0);
759 free(env->me_pghead);
760 env->me_pghead = NULL;
762 /* save to free list */
763 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
767 /* make sure last page of freeDB is touched and on freelist */
768 key.mv_size = MAXKEYSIZE+1;
770 mpp.mp_parent = NULL;
772 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
777 ULONG *idl = txn->mt_free_pgs;
778 DPRINTF("IDL write txn %lu root %lu num %lu",
779 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
780 for (i=0; i<idl[0]; i++) {
781 DPRINTF("IDL %lu", idl[i+1]);
785 /* write to last page of freeDB */
786 key.mv_size = sizeof(pgno_t);
787 key.mv_data = (char *)&txn->mt_txnid;
788 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
789 data.mv_data = txn->mt_free_pgs;
790 mdb_put(txn, FREE_DBI, &key, &data, 0);
793 /* Update DB root pointers. Their pages have already been
794 * touched so this is all in-place and cannot fail.
798 data.mv_size = sizeof(MDB_db);
800 for (i = 2; i < env->me_numdbs; i++) {
801 if (env->me_dbs[env->me_db_toggle][i].md_root != txn->mt_dbs[i].md_root) {
802 data.mv_data = &txn->mt_dbs[i];
803 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
806 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
807 data.mv_data = &txn->mt_dbs[i];
808 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
812 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
819 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
820 if (dp->p.mp_pgno != next) {
822 DPRINTF("committing %u dirty pages", n);
823 rc = writev(env->me_fd, iov, n);
827 DPRINTF("short write, filesystem full?");
829 DPRINTF("writev: %s", strerror(errno));
836 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
837 next = dp->p.mp_pgno;
839 DPRINTF("committing page %lu", dp->p.mp_pgno);
840 iov[n].iov_len = env->me_psize * dp->h.md_num;
841 iov[n].iov_base = &dp->p;
842 size += iov[n].iov_len;
843 next = dp->p.mp_pgno + dp->h.md_num;
844 /* clear dirty flag */
845 dp->p.mp_flags &= ~P_DIRTY;
846 if (++n >= MDB_COMMIT_PAGES) {
855 DPRINTF("committing %u dirty pages", n);
856 rc = writev(env->me_fd, iov, n);
860 DPRINTF("short write, filesystem full?");
862 DPRINTF("writev: %s", strerror(errno));
869 /* Drop the dirty pages.
871 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
872 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
873 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
877 if ((n = mdbenv_sync(env)) != 0 ||
878 (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
879 (n = mdbenv_sync(env)) != 0) {
885 /* update the DB tables */
887 int toggle = !env->me_db_toggle;
889 for (i = 0; i < env->me_numdbs; i++) {
890 if (env->me_dbs[toggle][i].md_root != txn->mt_dbs[i].md_root)
891 env->me_dbs[toggle][i] = txn->mt_dbs[i];
893 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
894 env->me_dbxs[i] = txn->mt_dbxs[i];
895 env->me_dbs[toggle][i] = txn->mt_dbs[i];
897 env->me_db_toggle = toggle;
898 env->me_numdbs = txn->mt_numdbs;
903 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
904 free(txn->mt_free_pgs);
905 free(txn->mt_u.dirty_queue);
916 mdbenv_read_header(MDB_env *env, MDB_meta *meta)
925 /* We don't know the page size yet, so use a minimum value.
928 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
930 } else if (rc != PAGESIZE) {
933 DPRINTF("read: %s", strerror(errno));
937 p = (MDB_page *)page;
939 if (!F_ISSET(p->mp_flags, P_META)) {
940 DPRINTF("page %lu not a meta page", p->mp_pgno);
945 if (m->mm_magic != MDB_MAGIC) {
946 DPRINTF("meta has invalid magic");
950 if (m->mm_version != MDB_VERSION) {
951 DPRINTF("database is version %u, expected version %u",
952 m->mm_version, MDB_VERSION);
956 memcpy(meta, m, sizeof(*m));
961 mdbenv_init_meta(MDB_env *env, MDB_meta *meta)
968 DPRINTF("writing new meta page");
969 psize = sysconf(_SC_PAGE_SIZE);
971 meta->mm_magic = MDB_MAGIC;
972 meta->mm_version = MDB_VERSION;
973 meta->mm_psize = psize;
974 meta->mm_last_pg = 1;
975 meta->mm_flags = env->me_flags & 0xffff;
976 #if __BYTE_ORDER == __LITTLE_ENDIAN
977 /* freeDB keys are pgno_t's, must compare in int order */
978 meta->mm_flags |= MDB_REVERSEKEY;
980 meta->mm_dbs[0].md_root = P_INVALID;
981 meta->mm_dbs[1].md_root = P_INVALID;
983 p = calloc(2, psize);
985 p->mp_flags = P_META;
988 memcpy(m, meta, sizeof(*meta));
990 q = (MDB_page *)((char *)p + psize);
993 q->mp_flags = P_META;
996 memcpy(m, meta, sizeof(*meta));
998 rc = write(env->me_fd, p, psize * 2);
1000 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1004 mdbenv_write_meta(MDB_txn *txn)
1012 assert(txn != NULL);
1013 assert(txn->mt_env != NULL);
1015 DPRINTF("writing meta page for root page %lu", txn->mt_dbs[MAIN_DBI].md_root);
1019 ptr = (char *)&meta;
1020 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1021 len = sizeof(MDB_meta) - off;
1024 meta.mm_dbs[0] = txn->mt_dbs[0];
1025 meta.mm_dbs[1] = txn->mt_dbs[1];
1026 meta.mm_last_pg = txn->mt_next_pgno - 1;
1027 meta.mm_txnid = txn->mt_txnid;
1029 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1030 off += env->me_psize;
1033 lseek(env->me_fd, off, SEEK_SET);
1034 rc = write(env->me_fd, ptr, len);
1036 DPRINTF("write failed, disk error?");
1044 mdbenv_read_meta(MDB_env *env, int *which)
1048 assert(env != NULL);
1050 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1053 if (env->me_meta != env->me_metas[toggle])
1054 env->me_meta = env->me_metas[toggle];
1058 DPRINTF("Using meta page %d", toggle);
1064 mdbenv_create(MDB_env **env)
1068 e = calloc(1, sizeof(*e));
1069 if (!e) return ENOMEM;
1071 e->me_maxreaders = DEFAULT_READERS;
1080 mdbenv_set_mapsize(MDB_env *env, size_t size)
1084 env->me_mapsize = size;
1089 mdbenv_set_maxdbs(MDB_env *env, int dbs)
1093 env->me_maxdbs = dbs;
1098 mdbenv_set_maxreaders(MDB_env *env, int readers)
1100 env->me_maxreaders = readers;
1105 mdbenv_get_maxreaders(MDB_env *env, int *readers)
1107 if (!env || !readers)
1109 *readers = env->me_maxreaders;
1114 mdbenv_open2(MDB_env *env, unsigned int flags)
1120 env->me_flags = flags;
1122 memset(&meta, 0, sizeof(meta));
1124 if ((i = mdbenv_read_header(env, &meta)) != 0) {
1127 DPRINTF("new mdbenv");
1131 if (!env->me_mapsize) {
1132 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1136 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1138 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1140 if (env->me_map == MAP_FAILED)
1144 meta.mm_mapsize = env->me_mapsize;
1145 if (flags & MDB_FIXEDMAP)
1146 meta.mm_address = env->me_map;
1147 i = mdbenv_init_meta(env, &meta);
1148 if (i != MDB_SUCCESS) {
1149 munmap(env->me_map, env->me_mapsize);
1153 env->me_psize = meta.mm_psize;
1155 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1156 env->me_metas[0] = METADATA(p);
1157 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1159 if ((i = mdbenv_read_meta(env, NULL)) != 0)
1162 DPRINTF("opened database version %u, pagesize %u",
1163 env->me_meta->mm_version, env->me_psize);
1164 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1165 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1166 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1167 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1168 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1169 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1175 mdbenv_reader_dest(void *ptr)
1177 MDB_reader *reader = ptr;
1179 reader->mr_txnid = 0;
1184 /* downgrade the exclusive lock on the region back to shared */
1186 mdbenv_share_locks(MDB_env *env)
1188 struct flock lock_info;
1190 env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1192 memset((void *)&lock_info, 0, sizeof(lock_info));
1193 lock_info.l_type = F_RDLCK;
1194 lock_info.l_whence = SEEK_SET;
1195 lock_info.l_start = 0;
1196 lock_info.l_len = 1;
1197 fcntl(env->me_lfd, F_SETLK, &lock_info);
1201 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1205 struct flock lock_info;
1209 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1213 /* Try to get exclusive lock. If we succeed, then
1214 * nobody is using the lock region and we should initialize it.
1216 memset((void *)&lock_info, 0, sizeof(lock_info));
1217 lock_info.l_type = F_WRLCK;
1218 lock_info.l_whence = SEEK_SET;
1219 lock_info.l_start = 0;
1220 lock_info.l_len = 1;
1221 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1225 lock_info.l_type = F_RDLCK;
1226 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1232 size = lseek(env->me_lfd, 0, SEEK_END);
1233 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1234 if (size < rsize && *excl) {
1235 if (ftruncate(env->me_lfd, rsize) != 0) {
1241 size = rsize - sizeof(MDB_txninfo);
1242 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1244 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1246 if (env->me_txns == MAP_FAILED) {
1251 pthread_mutexattr_t mattr;
1253 pthread_mutexattr_init(&mattr);
1254 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1255 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1256 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1257 env->me_txns->mt_version = MDB_VERSION;
1258 env->me_txns->mt_magic = MDB_MAGIC;
1259 env->me_txns->mt_txnid = 0;
1260 env->me_txns->mt_numreaders = 0;
1263 if (env->me_txns->mt_magic != MDB_MAGIC) {
1264 DPRINTF("lock region has invalid magic");
1267 if (env->me_txns->mt_version != MDB_VERSION) {
1268 DPRINTF("lock region is version %u, expected version %u",
1269 env->me_txns->mt_version, MDB_VERSION);
1272 if (errno != EACCES && errno != EAGAIN) {
1286 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1288 int oflags, rc, len, excl;
1289 char *lpath, *dpath;
1292 lpath = malloc(len + sizeof("/lock.mdb") + len + sizeof("/data.db"));
1295 dpath = lpath + len + sizeof("/lock.mdb");
1296 sprintf(lpath, "%s/lock.mdb", path);
1297 sprintf(dpath, "%s/data.mdb", path);
1299 rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1303 if (F_ISSET(flags, MDB_RDONLY))
1306 oflags = O_RDWR | O_CREAT;
1308 if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1311 if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1315 env->me_path = strdup(path);
1316 DPRINTF("opened dbenv %p", (void *) env);
1317 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1319 mdbenv_share_locks(env);
1320 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1321 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1322 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1332 mdbenv_close(MDB_env *env)
1341 munmap(env->me_map, env->me_mapsize);
1345 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1346 munmap(env->me_txns, size);
1352 /* Search for key within a leaf page, using binary search.
1353 * Returns the smallest entry larger or equal to the key.
1354 * If exactp is non-null, stores whether the found entry was an exact match
1355 * in *exactp (1 or 0).
1356 * If kip is non-null, stores the index of the found entry in *kip.
1357 * If no entry larger or equal to the key is found, returns NULL.
1360 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1361 int *exactp, unsigned int *kip)
1369 DPRINTF("searching %u keys in %s page %lu",
1371 IS_LEAF(mp) ? "leaf" : "branch",
1374 assert(NUMKEYS(mp) > 0);
1376 memset(&nodekey, 0, sizeof(nodekey));
1378 low = IS_LEAF(mp) ? 0 : 1;
1379 high = NUMKEYS(mp) - 1;
1380 while (low <= high) {
1381 i = (low + high) >> 1;
1382 node = NODEPTR(mp, i);
1384 nodekey.mv_size = node->mn_ksize;
1385 nodekey.mv_data = NODEKEY(node);
1387 if (txn->mt_dbxs[dbi].md_cmp)
1388 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1390 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1393 DPRINTF("found leaf index %u [%.*s], rc = %i",
1394 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1396 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1397 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1408 if (rc > 0) { /* Found entry is less than the key. */
1409 i++; /* Skip to get the smallest entry larger than key. */
1410 if (i >= NUMKEYS(mp))
1411 /* There is no entry larger or equal to the key. */
1415 *exactp = (rc == 0);
1416 if (kip) /* Store the key index if requested. */
1419 return NODEPTR(mp, i);
1423 cursor_pop_page(MDB_cursor *cursor)
1427 top = CURSOR_TOP(cursor);
1430 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1436 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1440 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1442 if ((ppage = calloc(1, sizeof(*ppage))) == NULL)
1444 ppage->mp_page = mp;
1445 CURSOR_PUSH(cursor, ppage);
1450 mdbenv_get_page(MDB_env *env, pgno_t pgno)
1453 MDB_txn *txn = env->me_txn;
1456 if (txn && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1458 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1459 if (dp->p.mp_pgno == pgno) {
1467 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
1473 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1474 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1476 MDB_page *mp = mpp->mp_page;
1479 if (cursor && cursor_push_page(cursor, mp) == NULL)
1482 while (IS_BRANCH(mp)) {
1486 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1487 assert(NUMKEYS(mp) > 1);
1488 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1490 if (key == NULL) /* Initialize cursor to first page. */
1492 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1493 /* cursor to last page */
1497 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1499 i = NUMKEYS(mp) - 1;
1507 DPRINTF("following index %u for key %.*s",
1508 i, (int)key->mv_size, (char *)key->mv_data);
1509 assert(i < NUMKEYS(mp));
1510 node = NODEPTR(mp, i);
1513 CURSOR_TOP(cursor)->mp_ki = i;
1515 mpp->mp_parent = mp;
1516 if ((mp = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
1521 if (cursor && cursor_push_page(cursor, mp) == NULL)
1525 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1526 if ((rc = mdb_touch(txn, mpp)) != 0)
1528 dh = ((MDB_dhead *)mpp->mp_page)-1;
1529 dh->md_parent = mpp->mp_parent;
1530 dh->md_pi = mpp->mp_pi;
1537 DPRINTF("internal error, index points to a %02X page!?",
1542 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1543 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1548 /* Search for the page a given key should be in.
1549 * Stores a pointer to the found page in *mpp.
1550 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1551 * If cursor is non-null, pushes parent pages on the cursor stack.
1552 * If modify is true, visited pages are updated with new page numbers.
1555 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1556 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1561 /* Choose which root page to start with. If a transaction is given
1562 * use the root page from the transaction, otherwise read the last
1563 * committed root page.
1565 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1566 DPRINTF("transaction has failed, must abort");
1569 root = txn->mt_dbs[dbi].md_root;
1571 if (root == P_INVALID) { /* Tree is empty. */
1572 DPRINTF("tree is empty");
1576 if ((mpp->mp_page = mdbenv_get_page(txn->mt_env, root)) == NULL)
1579 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1582 /* For sub-databases, update main root first */
1583 if (dbi > MAIN_DBI && txn->mt_dbs[dbi].md_root ==
1584 txn->mt_env->me_dbs[txn->mt_env->me_db_toggle][dbi].md_root) {
1586 rc = mdb_search_page(txn, 0, &txn->mt_dbxs[dbi].md_name,
1591 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1592 mpp->mp_parent = NULL;
1594 if ((rc = mdb_touch(txn, mpp)))
1596 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1600 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1604 mdb_read_data(MDB_env *env, MDB_node *leaf, MDB_val *data)
1606 MDB_page *omp; /* overflow mpage */
1609 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1610 data->mv_size = leaf->mn_dsize;
1611 data->mv_data = NODEDATA(leaf);
1615 /* Read overflow data.
1617 data->mv_size = leaf->mn_dsize;
1618 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1619 if ((omp = mdbenv_get_page(env, pgno)) == NULL) {
1620 DPRINTF("read overflow page %lu failed", pgno);
1623 data->mv_data = omp;
1629 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1630 MDB_val *key, MDB_val *data)
1638 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1640 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1644 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1647 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1649 rc = mdb_read_data(txn->mt_env, leaf, data);
1658 mdb_sibling(MDB_cursor *cursor, int move_right)
1662 MDB_ppage *parent, *top;
1665 top = CURSOR_TOP(cursor);
1666 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1667 return ENOENT; /* root has no siblings */
1670 DPRINTF("parent page is page %lu, index %u",
1671 parent->mp_page->mp_pgno, parent->mp_ki);
1673 cursor_pop_page(cursor);
1674 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1675 : (parent->mp_ki == 0)) {
1676 DPRINTF("no more keys left, moving to %s sibling",
1677 move_right ? "right" : "left");
1678 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1680 parent = CURSOR_TOP(cursor);
1686 DPRINTF("just moving to %s index key %u",
1687 move_right ? "right" : "left", parent->mp_ki);
1689 assert(IS_BRANCH(parent->mp_page));
1691 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1692 if ((mp = mdbenv_get_page(cursor->mc_txn->mt_env, indx->mn_pgno)) == NULL)
1695 mp->parent = parent->mp_page;
1696 mp->parent_index = parent->mp_ki;
1699 cursor_push_page(cursor, mp);
1705 mdb_set_key(MDB_node *node, MDB_val *key)
1710 key->mv_size = node->mn_ksize;
1711 key->mv_data = NODEKEY(node);
1717 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1723 if (cursor->mc_eof) {
1727 assert(cursor->mc_initialized);
1729 top = CURSOR_TOP(cursor);
1732 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1734 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1735 DPRINTF("=====> move to next sibling page");
1736 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1740 top = CURSOR_TOP(cursor);
1742 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1746 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1747 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1749 assert(IS_LEAF(mp));
1750 leaf = NODEPTR(mp, top->mp_ki);
1752 if (data && mdb_read_data(cursor->mc_txn->mt_env, leaf, data) != MDB_SUCCESS)
1755 return mdb_set_key(leaf, key);
1759 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1765 assert(cursor->mc_initialized);
1767 top = CURSOR_TOP(cursor);
1770 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1772 if (top->mp_ki == 0) {
1773 DPRINTF("=====> move to prev sibling page");
1774 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1777 top = CURSOR_TOP(cursor);
1779 top->mp_ki = NUMKEYS(mp) - 1;
1780 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1786 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1787 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1789 assert(IS_LEAF(mp));
1790 leaf = NODEPTR(mp, top->mp_ki);
1792 if (data && mdb_read_data(cursor->mc_txn->mt_env, leaf, data) != MDB_SUCCESS)
1795 return mdb_set_key(leaf, key);
1799 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1809 assert(key->mv_size > 0);
1811 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1812 if (rc != MDB_SUCCESS)
1814 assert(IS_LEAF(mpp.mp_page));
1816 top = CURSOR_TOP(cursor);
1817 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1818 if (exactp != NULL && !*exactp) {
1819 /* MDB_SET specified and not an exact match. */
1824 DPRINTF("===> inexact leaf not found, goto sibling");
1825 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1826 return rc; /* no entries matched */
1827 top = CURSOR_TOP(cursor);
1829 mpp.mp_page = top->mp_page;
1830 assert(IS_LEAF(mpp.mp_page));
1831 leaf = NODEPTR(mpp.mp_page, 0);
1834 cursor->mc_initialized = 1;
1837 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1840 rc = mdb_set_key(leaf, key);
1841 if (rc == MDB_SUCCESS) {
1842 DPRINTF("==> cursor placed on key %.*s",
1843 (int)key->mv_size, (char *)key->mv_data);
1851 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1857 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1858 if (rc != MDB_SUCCESS)
1860 assert(IS_LEAF(mpp.mp_page));
1862 leaf = NODEPTR(mpp.mp_page, 0);
1863 cursor->mc_initialized = 1;
1866 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1869 return mdb_set_key(leaf, key);
1873 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1881 lkey.mv_size = MAXKEYSIZE+1;
1882 lkey.mv_data = NULL;
1884 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
1885 if (rc != MDB_SUCCESS)
1887 assert(IS_LEAF(mpp.mp_page));
1889 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
1890 cursor->mc_initialized = 1;
1893 top = CURSOR_TOP(cursor);
1894 top->mp_ki = NUMKEYS(top->mp_page) - 1;
1896 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1899 return mdb_set_key(leaf, key);
1903 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1914 while (CURSOR_TOP(cursor) != NULL)
1915 cursor_pop_page(cursor);
1916 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1918 } else if (op == MDB_SET)
1919 rc = mdb_cursor_set(cursor, key, data, &exact);
1921 rc = mdb_cursor_set(cursor, key, data, NULL);
1924 if (!cursor->mc_initialized)
1925 rc = mdb_cursor_first(cursor, key, data);
1927 rc = mdb_cursor_next(cursor, key, data);
1930 if (!cursor->mc_initialized || cursor->mc_eof) {
1931 while (CURSOR_TOP(cursor) != NULL)
1932 cursor_pop_page(cursor);
1933 rc = mdb_cursor_last(cursor, key, data);
1935 rc = mdb_cursor_prev(cursor, key, data);
1938 while (CURSOR_TOP(cursor) != NULL)
1939 cursor_pop_page(cursor);
1940 rc = mdb_cursor_first(cursor, key, data);
1943 while (CURSOR_TOP(cursor) != NULL)
1944 cursor_pop_page(cursor);
1945 rc = mdb_cursor_last(cursor, key, data);
1948 DPRINTF("unhandled/unimplemented cursor operation %u", op);
1956 /* Allocate a page and initialize it
1959 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
1963 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
1965 DPRINTF("allocated new mpage %lu, page size %u",
1966 dp->p.mp_pgno, txn->mt_env->me_psize);
1967 dp->p.mp_flags = flags | P_DIRTY;
1968 dp->p.mp_lower = PAGEHDRSZ;
1969 dp->p.mp_upper = txn->mt_env->me_psize;
1971 if (IS_BRANCH(&dp->p))
1972 txn->mt_dbs[dbi].md_branch_pages++;
1973 else if (IS_LEAF(&dp->p))
1974 txn->mt_dbs[dbi].md_leaf_pages++;
1975 else if (IS_OVERFLOW(&dp->p)) {
1976 txn->mt_dbs[dbi].md_overflow_pages += num;
1977 dp->p.mp_pages = num;
1984 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
1988 sz = LEAFSIZE(key, data);
1989 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
1990 /* put on overflow page */
1991 sz -= data->mv_size - sizeof(pgno_t);
1994 return sz + sizeof(indx_t);
1998 mdb_branch_size(MDB_env *env, MDB_val *key)
2003 if (sz >= env->me_psize / MDB_MINKEYS) {
2004 /* put on overflow page */
2005 /* not implemented */
2006 /* sz -= key->size - sizeof(pgno_t); */
2009 return sz + sizeof(indx_t);
2013 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2014 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2017 size_t node_size = NODESIZE;
2020 MDB_dpage *ofp = NULL; /* overflow page */
2022 assert(mp->mp_upper >= mp->mp_lower);
2024 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2025 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2026 IS_LEAF(mp) ? "leaf" : "branch",
2027 mp->mp_pgno, indx, key ? key->mv_size : 0);
2030 node_size += key->mv_size;
2034 if (F_ISSET(flags, F_BIGDATA)) {
2035 /* Data already on overflow page. */
2036 node_size += sizeof(pgno_t);
2037 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2038 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2039 /* Put data on overflow page. */
2040 DPRINTF("data size is %zu, put on overflow page",
2042 node_size += sizeof(pgno_t);
2043 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2045 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2048 node_size += data->mv_size;
2052 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2053 DPRINTF("not enough room in page %lu, got %u ptrs",
2054 mp->mp_pgno, NUMKEYS(mp));
2055 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2056 mp->mp_upper - mp->mp_lower);
2057 DPRINTF("node size = %zu", node_size);
2061 /* Move higher pointers up one slot. */
2062 for (i = NUMKEYS(mp); i > indx; i--)
2063 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2065 /* Adjust free space offsets. */
2066 ofs = mp->mp_upper - node_size;
2067 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2068 mp->mp_ptrs[indx] = ofs;
2070 mp->mp_lower += sizeof(indx_t);
2072 /* Write the node data. */
2073 node = NODEPTR(mp, indx);
2074 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2075 node->mn_flags = flags;
2077 node->mn_dsize = data->mv_size;
2079 node->mn_pgno = pgno;
2082 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2087 if (F_ISSET(flags, F_BIGDATA))
2088 memcpy(node->mn_data + key->mv_size, data->mv_data,
2091 memcpy(node->mn_data + key->mv_size, data->mv_data,
2094 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2096 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2104 mdb_del_node(MDB_page *mp, indx_t indx)
2107 indx_t i, j, numkeys, ptr;
2111 DPRINTF("delete node %u on %s page %lu", indx,
2112 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2113 assert(indx < NUMKEYS(mp));
2115 node = NODEPTR(mp, indx);
2116 sz = NODESIZE + node->mn_ksize;
2118 if (F_ISSET(node->mn_flags, F_BIGDATA))
2119 sz += sizeof(pgno_t);
2121 sz += NODEDSZ(node);
2124 ptr = mp->mp_ptrs[indx];
2125 numkeys = NUMKEYS(mp);
2126 for (i = j = 0; i < numkeys; i++) {
2128 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2129 if (mp->mp_ptrs[i] < ptr)
2130 mp->mp_ptrs[j] += sz;
2135 base = (char *)mp + mp->mp_upper;
2136 memmove(base + sz, base, ptr - mp->mp_upper);
2138 mp->mp_lower -= sizeof(indx_t);
2143 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2147 if (txn == NULL || ret == NULL)
2150 if ((cursor = calloc(1, sizeof(*cursor))) != NULL) {
2151 SLIST_INIT(&cursor->mc_stack);
2152 cursor->mc_dbi = dbi;
2153 cursor->mc_txn = txn;
2162 mdb_cursor_close(MDB_cursor *cursor)
2164 if (cursor != NULL) {
2165 while (!CURSOR_EMPTY(cursor))
2166 cursor_pop_page(cursor);
2168 /* btree_close(cursor->bt); */
2174 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2176 indx_t ptr, i, numkeys;
2182 node = NODEPTR(mp, indx);
2183 ptr = mp->mp_ptrs[indx];
2184 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2186 (int)node->mn_ksize, (char *)NODEKEY(node),
2187 (int)key->mv_size, (char *)key->mv_data,
2190 delta = key->mv_size - node->mn_ksize;
2192 if (delta > 0 && SIZELEFT(mp) < delta) {
2193 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2197 numkeys = NUMKEYS(mp);
2198 for (i = 0; i < numkeys; i++) {
2199 if (mp->mp_ptrs[i] <= ptr)
2200 mp->mp_ptrs[i] -= delta;
2203 base = (char *)mp + mp->mp_upper;
2204 len = ptr - mp->mp_upper + NODESIZE;
2205 memmove(base - delta, base, len);
2206 mp->mp_upper -= delta;
2208 node = NODEPTR(mp, indx);
2209 node->mn_ksize = key->mv_size;
2212 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2217 /* Move a node from src to dst.
2220 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2221 MDB_pageparent *dst, indx_t dstindx)
2227 srcnode = NODEPTR(src->mp_page, srcindx);
2228 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2229 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2231 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2232 src->mp_page->mp_pgno,
2233 dstindx, dst->mp_page->mp_pgno);
2235 /* Mark src and dst as dirty. */
2236 if ((rc = mdb_touch(txn, src)) ||
2237 (rc = mdb_touch(txn, dst)))
2240 /* Add the node to the destination page.
2242 key.mv_size = srcnode->mn_ksize;
2243 key.mv_data = NODEKEY(srcnode);
2244 data.mv_size = NODEDSZ(srcnode);
2245 data.mv_data = NODEDATA(srcnode);
2246 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2248 if (rc != MDB_SUCCESS)
2251 /* Delete the node from the source page.
2253 mdb_del_node(src->mp_page, srcindx);
2255 /* Update the parent separators.
2257 if (srcindx == 0 && src->mp_pi != 0) {
2258 DPRINTF("update separator for source page %lu to [%.*s]",
2259 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2260 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2261 &key)) != MDB_SUCCESS)
2265 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2267 nullkey.mv_size = 0;
2268 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2271 if (dstindx == 0 && dst->mp_pi != 0) {
2272 DPRINTF("update separator for destination page %lu to [%.*s]",
2273 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2274 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2275 &key)) != MDB_SUCCESS)
2279 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2281 nullkey.mv_size = 0;
2282 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2289 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2298 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2300 assert(txn != NULL);
2301 assert(src->mp_parent); /* can't merge root page */
2302 assert(dst->mp_parent);
2304 /* Mark src and dst as dirty. */
2305 if ((rc = mdb_touch(txn, src)) ||
2306 (rc = mdb_touch(txn, dst)))
2309 /* Move all nodes from src to dst.
2311 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2312 srcnode = NODEPTR(src->mp_page, i);
2314 key.mv_size = srcnode->mn_ksize;
2315 key.mv_data = NODEKEY(srcnode);
2316 data.mv_size = NODEDSZ(srcnode);
2317 data.mv_data = NODEDATA(srcnode);
2318 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2319 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2320 if (rc != MDB_SUCCESS)
2324 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2325 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2327 /* Unlink the src page from parent.
2329 mdb_del_node(src->mp_parent, src->mp_pi);
2330 if (src->mp_pi == 0) {
2332 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2336 if (IS_LEAF(src->mp_page))
2337 txn->mt_dbs[dbi].md_leaf_pages--;
2339 txn->mt_dbs[dbi].md_branch_pages--;
2341 mpp.mp_page = src->mp_parent;
2342 dh = (MDB_dhead *)src->mp_parent;
2344 mpp.mp_parent = dh->md_parent;
2345 mpp.mp_pi = dh->md_pi;
2347 return mdb_rebalance(txn, dbi, &mpp);
2350 #define FILL_THRESHOLD 250
2353 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2358 indx_t si = 0, di = 0;
2360 assert(txn != NULL);
2361 assert(mpp != NULL);
2363 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2364 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2365 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2367 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2368 DPRINTF("no need to rebalance page %lu, above fill threshold",
2369 mpp->mp_page->mp_pgno);
2373 if (mpp->mp_parent == NULL) {
2374 if (NUMKEYS(mpp->mp_page) == 0) {
2375 DPRINTF("tree is completely empty");
2376 txn->mt_dbs[dbi].md_root = P_INVALID;
2377 txn->mt_dbs[dbi].md_depth--;
2378 txn->mt_dbs[dbi].md_leaf_pages--;
2379 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2380 DPRINTF("collapsing root page!");
2381 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2382 if ((root = mdbenv_get_page(txn->mt_env, txn->mt_dbs[dbi].md_root)) == NULL)
2384 txn->mt_dbs[dbi].md_depth--;
2385 txn->mt_dbs[dbi].md_branch_pages--;
2387 DPRINTF("root page doesn't need rebalancing");
2391 /* The parent (branch page) must have at least 2 pointers,
2392 * otherwise the tree is invalid.
2394 assert(NUMKEYS(mpp->mp_parent) > 1);
2396 /* Leaf page fill factor is below the threshold.
2397 * Try to move keys from left or right neighbor, or
2398 * merge with a neighbor page.
2403 if (mpp->mp_pi == 0) {
2404 /* We're the leftmost leaf in our parent.
2406 DPRINTF("reading right neighbor");
2407 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2408 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2410 npp.mp_pi = mpp->mp_pi + 1;
2412 di = NUMKEYS(mpp->mp_page);
2414 /* There is at least one neighbor to the left.
2416 DPRINTF("reading left neighbor");
2417 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2418 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2420 npp.mp_pi = mpp->mp_pi - 1;
2421 si = NUMKEYS(npp.mp_page) - 1;
2424 npp.mp_parent = mpp->mp_parent;
2426 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2427 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2429 /* If the neighbor page is above threshold and has at least two
2430 * keys, move one key from it.
2432 * Otherwise we should try to merge them.
2434 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2435 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2436 else { /* FIXME: if (has_enough_room()) */
2437 if (mpp->mp_pi == 0)
2438 return mdb_merge(txn, dbi, &npp, mpp);
2440 return mdb_merge(txn, dbi, mpp, &npp);
2445 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2449 /* add overflow pages to free list */
2450 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2454 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2455 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2456 for (i=0; i<ovpages; i++) {
2457 DPRINTF("freed ov page %lu", pg);
2458 mdb_idl_insert(txn->mt_free_pgs, pg);
2462 mdb_del_node(mpp->mp_page, ki);
2463 txn->mt_dbs[dbi].md_entries--;
2464 rc = mdb_rebalance(txn, dbi, mpp);
2465 if (rc != MDB_SUCCESS)
2466 txn->mt_flags |= MDB_TXN_ERROR;
2472 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2473 MDB_val *key, MDB_val *data)
2480 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2482 assert(key != NULL);
2484 if (txn == NULL || dbi >= txn->mt_numdbs)
2487 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2491 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2495 mpp.mp_parent = NULL;
2497 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2500 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2501 if (leaf == NULL || !exact) {
2505 if (data && (rc = mdb_read_data(txn->mt_env, leaf, data)) != MDB_SUCCESS)
2508 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2511 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2512 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2513 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2514 * refer to a node in the new right sibling page.
2517 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2518 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2521 int rc = MDB_SUCCESS, ins_new = 0;
2524 unsigned int i, j, split_indx;
2526 MDB_val sepkey, rkey, rdata;
2528 MDB_dpage *mdp, *rdp, *pdp;
2531 assert(txn != NULL);
2533 dh = ((MDB_dhead *)*mpp) - 1;
2534 mdp = (MDB_dpage *)dh;
2535 newindx = *newindxp;
2537 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2538 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2539 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2541 if (mdp->h.md_parent == NULL) {
2542 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2545 mdp->h.md_parent = &pdp->p;
2546 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2547 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2548 txn->mt_dbs[dbi].md_depth++;
2550 /* Add left (implicit) pointer. */
2551 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2552 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2555 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2558 /* Create a right sibling. */
2559 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2561 rdp->h.md_parent = mdp->h.md_parent;
2562 rdp->h.md_pi = mdp->h.md_pi + 1;
2563 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2565 /* Move half of the keys to the right sibling. */
2566 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2568 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2569 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2570 mdp->p.mp_lower = PAGEHDRSZ;
2571 mdp->p.mp_upper = txn->mt_env->me_psize;
2573 split_indx = NUMKEYS(copy) / 2 + 1;
2575 /* First find the separating key between the split pages.
2577 memset(&sepkey, 0, sizeof(sepkey));
2578 if (newindx == split_indx) {
2579 sepkey.mv_size = newkey->mv_size;
2580 sepkey.mv_data = newkey->mv_data;
2582 node = NODEPTR(copy, split_indx);
2583 sepkey.mv_size = node->mn_ksize;
2584 sepkey.mv_data = NODEKEY(node);
2587 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2589 /* Copy separator key to the parent.
2591 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2592 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2593 &sepkey, NULL, rdp->p.mp_pgno);
2595 /* Right page might now have changed parent.
2596 * Check if left page also changed parent.
2598 if (rdp->h.md_parent != mdp->h.md_parent &&
2599 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2600 mdp->h.md_parent = rdp->h.md_parent;
2601 mdp->h.md_pi = rdp->h.md_pi - 1;
2604 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2605 &sepkey, NULL, rdp->p.mp_pgno, 0);
2607 if (rc != MDB_SUCCESS) {
2612 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2613 if (i < split_indx) {
2614 /* Re-insert in left sibling. */
2617 /* Insert in right sibling. */
2618 if (i == split_indx)
2619 /* Reset insert index for right sibling. */
2620 j = (i == newindx && ins_new);
2624 if (i == newindx && !ins_new) {
2625 /* Insert the original entry that caused the split. */
2626 rkey.mv_data = newkey->mv_data;
2627 rkey.mv_size = newkey->mv_size;
2628 if (IS_LEAF(&mdp->p)) {
2629 rdata.mv_data = newdata->mv_data;
2630 rdata.mv_size = newdata->mv_size;
2637 /* Update page and index for the new key. */
2640 } else if (i == NUMKEYS(copy)) {
2643 node = NODEPTR(copy, i);
2644 rkey.mv_data = NODEKEY(node);
2645 rkey.mv_size = node->mn_ksize;
2646 if (IS_LEAF(&mdp->p)) {
2647 rdata.mv_data = NODEDATA(node);
2648 rdata.mv_size = node->mn_dsize;
2650 pgno = node->mn_pgno;
2651 flags = node->mn_flags;
2656 if (!IS_LEAF(&mdp->p) && j == 0) {
2657 /* First branch index doesn't need key data. */
2661 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2669 mdb_put(MDB_txn *txn, MDB_dbi dbi,
2670 MDB_val *key, MDB_val *data, unsigned int flags)
2672 int rc = MDB_SUCCESS, exact;
2677 assert(key != NULL);
2678 assert(data != NULL);
2683 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2687 if (txn->mt_env->me_txn != txn) {
2691 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2695 DPRINTF("==> put key %.*s, size %zu, data size %zu",
2696 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2698 mpp.mp_parent = NULL;
2700 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2701 if (rc == MDB_SUCCESS) {
2702 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2703 if (leaf && exact) {
2704 if (F_ISSET(flags, MDB_NOOVERWRITE)) {
2705 DPRINTF("duplicate key %.*s",
2706 (int)key->mv_size, (char *)key->mv_data);
2709 /* same size, just replace it */
2710 if (NODEDSZ(leaf) == data->mv_size) {
2711 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2714 mdb_del_node(mpp.mp_page, ki);
2716 if (leaf == NULL) { /* append if not found */
2717 ki = NUMKEYS(mpp.mp_page);
2718 DPRINTF("appending key at index %i", ki);
2720 } else if (rc == ENOENT) {
2722 /* new file, just write a root leaf page */
2723 DPRINTF("allocating new root leaf page");
2724 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2727 mpp.mp_page = &dp->p;
2728 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
2729 txn->mt_dbs[dbi].md_depth++;
2735 assert(IS_LEAF(mpp.mp_page));
2736 DPRINTF("there are %u keys, should insert new key at index %i",
2737 NUMKEYS(mpp.mp_page), ki);
2739 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2740 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2742 /* There is room already in this leaf page. */
2743 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2746 if (rc != MDB_SUCCESS)
2747 txn->mt_flags |= MDB_TXN_ERROR;
2749 txn->mt_dbs[dbi].md_entries++;
2756 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
2761 *arg = env->me_flags;
2766 mdbenv_get_path(MDB_env *env, const char **arg)
2771 *arg = env->me_path;
2776 mdbenv_stat(MDB_env *env, MDB_stat *arg)
2778 if (env == NULL || arg == NULL)
2781 arg->ms_psize = env->me_psize;
2782 arg->ms_depth = env->me_meta->mm_dbs[MAIN_DBI].md_depth;
2783 arg->ms_branch_pages = env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages;
2784 arg->ms_leaf_pages = env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages;
2785 arg->ms_overflow_pages = env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages;
2786 arg->ms_entries = env->me_meta->mm_dbs[MAIN_DBI].md_entries;
2791 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
2804 /* Is the DB already open? */
2806 for (i=2; i<txn->mt_numdbs; i++) {
2807 if (len == txn->mt_dbxs[i].md_name.mv_size &&
2808 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
2814 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
2817 /* Find the DB info */
2819 key.mv_data = (void *)name;
2820 rc = mdb_get(txn, MAIN_DBI, &key, &data);
2822 /* Create if requested */
2823 if (rc == ENOENT && (flags & MDB_CREATE)) {
2825 data.mv_size = sizeof(MDB_db);
2826 data.mv_data = &dummy;
2827 memset(&dummy, 0, sizeof(dummy));
2828 dummy.md_root = P_INVALID;
2829 dummy.md_flags = flags & 0xffff;
2830 rc = mdb_put(txn, 0, &key, &data, 0);
2833 /* OK, got info, add to table */
2834 if (rc == MDB_SUCCESS) {
2835 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
2836 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
2837 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
2838 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
2839 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
2840 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
2841 *dbi = txn->mt_numdbs;
2848 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
2850 if (txn == NULL || arg == NULL)
2853 arg->ms_psize = txn->mt_env->me_psize;
2854 arg->ms_depth = txn->mt_dbs[dbi].md_depth;
2855 arg->ms_branch_pages = txn->mt_dbs[dbi].md_branch_pages;
2856 arg->ms_leaf_pages = txn->mt_dbs[dbi].md_leaf_pages;
2857 arg->ms_overflow_pages = txn->mt_dbs[dbi].md_overflow_pages;
2858 arg->ms_entries = txn->mt_dbs[dbi].md_entries;
2863 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
2866 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
2868 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
2869 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
2870 txn->mt_dbxs[dbi].md_name.mv_size = 0;