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_set(MDB_cursor *cursor,
366 MDB_val *key, MDB_val *data, int *exactp);
367 static int mdb_cursor_first(MDB_cursor *cursor,
368 MDB_val *key, MDB_val *data);
369 static int mdb_cursor_last(MDB_cursor *cursor,
370 MDB_val *key, MDB_val *data);
372 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
374 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
376 static int memncmp(const void *s1, size_t n1,
377 const void *s2, size_t n2);
378 static int memnrcmp(const void *s1, size_t n1,
379 const void *s2, size_t n2);
382 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
384 int diff, len_diff = -1;
387 len_diff = (n1 > n2);
390 diff = memcmp(s1, s2, n1);
391 return diff ? diff : len_diff;
395 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
397 const unsigned char *p1, *p2, *p1_lim;
404 p1 = (const unsigned char *)s1 + n1 - 1;
405 p2 = (const unsigned char *)s2 + n2 - 1;
407 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
409 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
415 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
417 return txn->mt_dbxs[dbi].md_cmp(a, b);
421 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
423 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_REVERSEKEY))
424 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
426 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
429 /* Allocate new page(s) for writing */
431 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
434 pgno_t pgno = P_INVALID;
435 ULONG oldest = txn->mt_txnid - 2;
437 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
438 /* See if there's anything in the free DB */
443 mpp.mp_parent = NULL;
445 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
446 leaf = NODEPTR(mpp.mp_page, 0);
447 kptr = (ULONG *)NODEKEY(leaf);
449 /* It's potentially usable, unless there are still
450 * older readers outstanding. Grab it.
452 if (oldest > *kptr) {
457 mdb_read_data(txn->mt_env, leaf, &data);
458 idl = (ULONG *)data.mv_data;
459 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
460 mop->mo_next = txn->mt_env->me_pghead;
461 mop->mo_txnid = *kptr;
462 txn->mt_env->me_pghead = mop;
463 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
468 DPRINTF("IDL read txn %lu root %lu num %lu",
469 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
470 for (i=0; i<idl[0]; i++) {
471 DPRINTF("IDL %lu", idl[i+1]);
475 /* drop this IDL from the DB */
476 mpp.mp_parent = NULL;
478 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
479 leaf = NODEPTR(mpp.mp_page, 0);
480 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
483 if (txn->mt_env->me_pghead) {
485 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
486 ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
489 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
491 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
492 MDB_oldpages *mop = txn->mt_env->me_pghead;
493 txn->mt_oldest = oldest;
495 /* FIXME: For now, always use fresh pages. We
496 * really ought to search the free list for a
501 /* peel pages off tail, so we only have to truncate the list */
502 pgno = MDB_IDL_LAST(mop->mo_pages);
503 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
505 if (mop->mo_pages[2] > mop->mo_pages[1])
506 mop->mo_pages[0] = 0;
510 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
511 txn->mt_env->me_pghead = mop->mo_next;
518 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
521 dp->h.md_parent = parent;
522 dp->h.md_pi = parent_idx;
523 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
524 if (pgno == P_INVALID) {
525 dp->p.mp_pgno = txn->mt_next_pgno;
526 txn->mt_next_pgno += num;
528 dp->p.mp_pgno = pgno;
534 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
537 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
539 MDB_page *mp = pp->mp_page;
544 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
546 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
548 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
549 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
550 pgno = dp->p.mp_pgno;
551 memcpy(&dp->p, mp, txn->mt_env->me_psize);
554 mp->mp_flags |= P_DIRTY;
556 /* Update the page number to new touched page. */
557 if (pp->mp_parent != NULL)
558 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
565 mdbenv_sync(MDB_env *env)
568 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
569 if (fsync(env->me_fd))
576 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
581 if ((txn = calloc(1, sizeof(*txn))) == NULL) {
582 DPRINTF("calloc: %s", strerror(errno));
587 txn->mt_flags |= MDB_TXN_RDONLY;
589 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
590 if (txn->mt_u.dirty_queue == NULL) {
594 STAILQ_INIT(txn->mt_u.dirty_queue);
596 pthread_mutex_lock(&env->me_txns->mt_wmutex);
597 env->me_txns->mt_txnid++;
598 txn->mt_free_pgs = malloc(MDB_IDL_UM_SIZEOF);
599 if (txn->mt_free_pgs == NULL) {
600 free(txn->mt_u.dirty_queue);
604 txn->mt_free_pgs[0] = 0;
607 txn->mt_txnid = env->me_txns->mt_txnid;
609 MDB_reader *r = pthread_getspecific(env->me_txkey);
612 pthread_mutex_lock(&env->me_txns->mt_mutex);
613 for (i=0; i<env->me_maxreaders; i++) {
614 if (env->me_txns->mt_readers[i].mr_pid == 0) {
615 env->me_txns->mt_readers[i].mr_pid = getpid();
616 env->me_txns->mt_readers[i].mr_tid = pthread_self();
617 r = &env->me_txns->mt_readers[i];
618 pthread_setspecific(env->me_txkey, r);
619 if (i >= env->me_txns->mt_numreaders)
620 env->me_txns->mt_numreaders = i+1;
624 pthread_mutex_unlock(&env->me_txns->mt_mutex);
625 if (i == env->me_maxreaders) {
629 r->mr_txnid = txn->mt_txnid;
630 txn->mt_u.reader = r;
637 if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
642 /* Copy the DB arrays */
643 txn->mt_numdbs = env->me_numdbs;
644 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
645 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
646 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
647 if (txn->mt_numdbs > 2)
648 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
649 (txn->mt_numdbs - 2) * sizeof(MDB_db));
653 txn->mt_flags |= MDB_TXN_METOGGLE;
654 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
657 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
658 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
665 mdb_txn_abort(MDB_txn *txn)
674 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
675 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
679 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
680 txn->mt_u.reader->mr_txnid = 0;
683 /* Discard all dirty pages. */
684 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
685 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
686 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
689 free(txn->mt_free_pgs);
690 free(txn->mt_u.dirty_queue);
692 while ((mop = txn->mt_env->me_pghead)) {
693 txn->mt_env->me_pghead = mop->mo_next;
698 env->me_txns->mt_txnid--;
699 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
706 mdb_txn_commit(MDB_txn *txn)
715 struct iovec iov[MDB_COMMIT_PAGES];
718 assert(txn->mt_env != NULL);
722 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
723 DPRINTF("attempt to commit read-only transaction");
728 if (txn != env->me_txn) {
729 DPRINTF("attempt to commit unknown transaction");
734 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
735 DPRINTF("error flag is set, can't commit");
740 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
743 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
744 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
746 /* should only be one record now */
747 if (env->me_pghead) {
751 mop = env->me_pghead;
752 key.mv_size = sizeof(pgno_t);
753 key.mv_data = (char *)&mop->mo_txnid;
754 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
755 data.mv_data = mop->mo_pages;
756 mdb_put(txn, FREE_DBI, &key, &data, 0);
757 free(env->me_pghead);
758 env->me_pghead = NULL;
760 /* save to free list */
761 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
765 /* make sure last page of freeDB is touched and on freelist */
766 key.mv_size = MAXKEYSIZE+1;
768 mpp.mp_parent = NULL;
770 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
775 ULONG *idl = txn->mt_free_pgs;
776 DPRINTF("IDL write txn %lu root %lu num %lu",
777 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
778 for (i=0; i<idl[0]; i++) {
779 DPRINTF("IDL %lu", idl[i+1]);
783 /* write to last page of freeDB */
784 key.mv_size = sizeof(pgno_t);
785 key.mv_data = (char *)&txn->mt_txnid;
786 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
787 data.mv_data = txn->mt_free_pgs;
788 mdb_put(txn, FREE_DBI, &key, &data, 0);
791 /* Update DB root pointers. Their pages have already been
792 * touched so this is all in-place and cannot fail.
796 data.mv_size = sizeof(MDB_db);
798 for (i = 2; i < env->me_numdbs; i++) {
799 if (env->me_dbs[env->me_db_toggle][i].md_root != txn->mt_dbs[i].md_root) {
800 data.mv_data = &txn->mt_dbs[i];
801 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
804 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
805 data.mv_data = &txn->mt_dbs[i];
806 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
810 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
817 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
818 if (dp->p.mp_pgno != next) {
820 DPRINTF("committing %u dirty pages", n);
821 rc = writev(env->me_fd, iov, n);
825 DPRINTF("short write, filesystem full?");
827 DPRINTF("writev: %s", strerror(errno));
834 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
835 next = dp->p.mp_pgno;
837 DPRINTF("committing page %lu", dp->p.mp_pgno);
838 iov[n].iov_len = env->me_psize * dp->h.md_num;
839 iov[n].iov_base = &dp->p;
840 size += iov[n].iov_len;
841 next = dp->p.mp_pgno + dp->h.md_num;
842 /* clear dirty flag */
843 dp->p.mp_flags &= ~P_DIRTY;
844 if (++n >= MDB_COMMIT_PAGES) {
853 DPRINTF("committing %u dirty pages", n);
854 rc = writev(env->me_fd, iov, n);
858 DPRINTF("short write, filesystem full?");
860 DPRINTF("writev: %s", strerror(errno));
867 /* Drop the dirty pages.
869 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
870 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
871 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
875 if ((n = mdbenv_sync(env)) != 0 ||
876 (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
877 (n = mdbenv_sync(env)) != 0) {
883 /* update the DB tables */
885 int toggle = !env->me_db_toggle;
887 for (i = 0; i < env->me_numdbs; i++) {
888 if (env->me_dbs[toggle][i].md_root != txn->mt_dbs[i].md_root)
889 env->me_dbs[toggle][i] = txn->mt_dbs[i];
891 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
892 env->me_dbxs[i] = txn->mt_dbxs[i];
893 env->me_dbs[toggle][i] = txn->mt_dbs[i];
895 env->me_db_toggle = toggle;
896 env->me_numdbs = txn->mt_numdbs;
901 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
902 free(txn->mt_free_pgs);
903 free(txn->mt_u.dirty_queue);
914 mdbenv_read_header(MDB_env *env, MDB_meta *meta)
923 /* We don't know the page size yet, so use a minimum value.
926 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
928 } else if (rc != PAGESIZE) {
931 DPRINTF("read: %s", strerror(errno));
935 p = (MDB_page *)page;
937 if (!F_ISSET(p->mp_flags, P_META)) {
938 DPRINTF("page %lu not a meta page", p->mp_pgno);
943 if (m->mm_magic != MDB_MAGIC) {
944 DPRINTF("meta has invalid magic");
948 if (m->mm_version != MDB_VERSION) {
949 DPRINTF("database is version %u, expected version %u",
950 m->mm_version, MDB_VERSION);
954 memcpy(meta, m, sizeof(*m));
959 mdbenv_init_meta(MDB_env *env, MDB_meta *meta)
966 DPRINTF("writing new meta page");
967 psize = sysconf(_SC_PAGE_SIZE);
969 meta->mm_magic = MDB_MAGIC;
970 meta->mm_version = MDB_VERSION;
971 meta->mm_psize = psize;
972 meta->mm_last_pg = 1;
973 meta->mm_flags = env->me_flags & 0xffff;
974 #if __BYTE_ORDER == __LITTLE_ENDIAN
975 /* freeDB keys are pgno_t's, must compare in int order */
976 meta->mm_flags |= MDB_REVERSEKEY;
978 meta->mm_dbs[0].md_root = P_INVALID;
979 meta->mm_dbs[1].md_root = P_INVALID;
981 p = calloc(2, psize);
983 p->mp_flags = P_META;
986 memcpy(m, meta, sizeof(*meta));
988 q = (MDB_page *)((char *)p + psize);
991 q->mp_flags = P_META;
994 memcpy(m, meta, sizeof(*meta));
996 rc = write(env->me_fd, p, psize * 2);
998 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1002 mdbenv_write_meta(MDB_txn *txn)
1010 assert(txn != NULL);
1011 assert(txn->mt_env != NULL);
1013 DPRINTF("writing meta page for root page %lu", txn->mt_dbs[MAIN_DBI].md_root);
1017 ptr = (char *)&meta;
1018 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1019 len = sizeof(MDB_meta) - off;
1022 meta.mm_dbs[0] = txn->mt_dbs[0];
1023 meta.mm_dbs[1] = txn->mt_dbs[1];
1024 meta.mm_last_pg = txn->mt_next_pgno - 1;
1025 meta.mm_txnid = txn->mt_txnid;
1027 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1028 off += env->me_psize;
1031 lseek(env->me_fd, off, SEEK_SET);
1032 rc = write(env->me_fd, ptr, len);
1034 DPRINTF("write failed, disk error?");
1042 mdbenv_read_meta(MDB_env *env, int *which)
1046 assert(env != NULL);
1048 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1051 if (env->me_meta != env->me_metas[toggle])
1052 env->me_meta = env->me_metas[toggle];
1056 DPRINTF("Using meta page %d", toggle);
1062 mdbenv_create(MDB_env **env)
1066 e = calloc(1, sizeof(*e));
1067 if (!e) return ENOMEM;
1069 e->me_maxreaders = DEFAULT_READERS;
1078 mdbenv_set_mapsize(MDB_env *env, size_t size)
1082 env->me_mapsize = size;
1087 mdbenv_set_maxdbs(MDB_env *env, int dbs)
1091 env->me_maxdbs = dbs;
1096 mdbenv_set_maxreaders(MDB_env *env, int readers)
1098 env->me_maxreaders = readers;
1103 mdbenv_get_maxreaders(MDB_env *env, int *readers)
1105 if (!env || !readers)
1107 *readers = env->me_maxreaders;
1112 mdbenv_open2(MDB_env *env, unsigned int flags)
1118 env->me_flags = flags;
1120 memset(&meta, 0, sizeof(meta));
1122 if ((i = mdbenv_read_header(env, &meta)) != 0) {
1125 DPRINTF("new mdbenv");
1129 if (!env->me_mapsize) {
1130 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1134 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1136 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1138 if (env->me_map == MAP_FAILED)
1142 meta.mm_mapsize = env->me_mapsize;
1143 if (flags & MDB_FIXEDMAP)
1144 meta.mm_address = env->me_map;
1145 i = mdbenv_init_meta(env, &meta);
1146 if (i != MDB_SUCCESS) {
1147 munmap(env->me_map, env->me_mapsize);
1151 env->me_psize = meta.mm_psize;
1153 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1154 env->me_metas[0] = METADATA(p);
1155 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1157 if ((i = mdbenv_read_meta(env, NULL)) != 0)
1160 DPRINTF("opened database version %u, pagesize %u",
1161 env->me_meta->mm_version, env->me_psize);
1162 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1163 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1164 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1165 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1166 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1167 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1173 mdbenv_reader_dest(void *ptr)
1175 MDB_reader *reader = ptr;
1177 reader->mr_txnid = 0;
1182 /* downgrade the exclusive lock on the region back to shared */
1184 mdbenv_share_locks(MDB_env *env)
1186 struct flock lock_info;
1188 env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1190 memset((void *)&lock_info, 0, sizeof(lock_info));
1191 lock_info.l_type = F_RDLCK;
1192 lock_info.l_whence = SEEK_SET;
1193 lock_info.l_start = 0;
1194 lock_info.l_len = 1;
1195 fcntl(env->me_lfd, F_SETLK, &lock_info);
1199 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1203 struct flock lock_info;
1207 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1211 /* Try to get exclusive lock. If we succeed, then
1212 * nobody is using the lock region and we should initialize it.
1214 memset((void *)&lock_info, 0, sizeof(lock_info));
1215 lock_info.l_type = F_WRLCK;
1216 lock_info.l_whence = SEEK_SET;
1217 lock_info.l_start = 0;
1218 lock_info.l_len = 1;
1219 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1223 lock_info.l_type = F_RDLCK;
1224 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1230 size = lseek(env->me_lfd, 0, SEEK_END);
1231 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1232 if (size < rsize && *excl) {
1233 if (ftruncate(env->me_lfd, rsize) != 0) {
1239 size = rsize - sizeof(MDB_txninfo);
1240 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1242 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1244 if (env->me_txns == MAP_FAILED) {
1249 pthread_mutexattr_t mattr;
1251 pthread_mutexattr_init(&mattr);
1252 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1253 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1254 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1255 env->me_txns->mt_version = MDB_VERSION;
1256 env->me_txns->mt_magic = MDB_MAGIC;
1257 env->me_txns->mt_txnid = 0;
1258 env->me_txns->mt_numreaders = 0;
1261 if (env->me_txns->mt_magic != MDB_MAGIC) {
1262 DPRINTF("lock region has invalid magic");
1265 if (env->me_txns->mt_version != MDB_VERSION) {
1266 DPRINTF("lock region is version %u, expected version %u",
1267 env->me_txns->mt_version, MDB_VERSION);
1270 if (errno != EACCES && errno != EAGAIN) {
1284 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1286 int oflags, rc, len, excl;
1287 char *lpath, *dpath;
1290 lpath = malloc(len + sizeof("/lock.mdb") + len + sizeof("/data.db"));
1293 dpath = lpath + len + sizeof("/lock.mdb");
1294 sprintf(lpath, "%s/lock.mdb", path);
1295 sprintf(dpath, "%s/data.mdb", path);
1297 rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1301 if (F_ISSET(flags, MDB_RDONLY))
1304 oflags = O_RDWR | O_CREAT;
1306 if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1309 if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1313 env->me_path = strdup(path);
1314 DPRINTF("opened dbenv %p", (void *) env);
1315 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1317 mdbenv_share_locks(env);
1318 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1319 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1320 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1330 mdbenv_close(MDB_env *env)
1339 munmap(env->me_map, env->me_mapsize);
1343 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1344 munmap(env->me_txns, size);
1350 /* Search for key within a leaf page, using binary search.
1351 * Returns the smallest entry larger or equal to the key.
1352 * If exactp is non-null, stores whether the found entry was an exact match
1353 * in *exactp (1 or 0).
1354 * If kip is non-null, stores the index of the found entry in *kip.
1355 * If no entry larger or equal to the key is found, returns NULL.
1358 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1359 int *exactp, unsigned int *kip)
1367 DPRINTF("searching %u keys in %s page %lu",
1369 IS_LEAF(mp) ? "leaf" : "branch",
1372 assert(NUMKEYS(mp) > 0);
1374 memset(&nodekey, 0, sizeof(nodekey));
1376 low = IS_LEAF(mp) ? 0 : 1;
1377 high = NUMKEYS(mp) - 1;
1378 while (low <= high) {
1379 i = (low + high) >> 1;
1380 node = NODEPTR(mp, i);
1382 nodekey.mv_size = node->mn_ksize;
1383 nodekey.mv_data = NODEKEY(node);
1385 if (txn->mt_dbxs[dbi].md_cmp)
1386 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1388 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1391 DPRINTF("found leaf index %u [%.*s], rc = %i",
1392 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1394 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1395 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1406 if (rc > 0) { /* Found entry is less than the key. */
1407 i++; /* Skip to get the smallest entry larger than key. */
1408 if (i >= NUMKEYS(mp))
1409 /* There is no entry larger or equal to the key. */
1413 *exactp = (rc == 0);
1414 if (kip) /* Store the key index if requested. */
1417 return NODEPTR(mp, i);
1421 cursor_pop_page(MDB_cursor *cursor)
1425 top = CURSOR_TOP(cursor);
1428 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1434 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1438 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1440 if ((ppage = calloc(1, sizeof(*ppage))) == NULL)
1442 ppage->mp_page = mp;
1443 CURSOR_PUSH(cursor, ppage);
1448 mdbenv_get_page(MDB_env *env, pgno_t pgno)
1451 MDB_txn *txn = env->me_txn;
1454 if (txn && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1456 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1457 if (dp->p.mp_pgno == pgno) {
1465 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
1471 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1472 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1474 MDB_page *mp = mpp->mp_page;
1477 if (cursor && cursor_push_page(cursor, mp) == NULL)
1480 while (IS_BRANCH(mp)) {
1484 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1485 assert(NUMKEYS(mp) > 1);
1486 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1488 if (key == NULL) /* Initialize cursor to first page. */
1490 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1491 /* cursor to last page */
1495 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1497 i = NUMKEYS(mp) - 1;
1505 DPRINTF("following index %u for key %.*s",
1506 i, (int)key->mv_size, (char *)key->mv_data);
1507 assert(i < NUMKEYS(mp));
1508 node = NODEPTR(mp, i);
1511 CURSOR_TOP(cursor)->mp_ki = i;
1513 mpp->mp_parent = mp;
1514 if ((mp = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
1519 if (cursor && cursor_push_page(cursor, mp) == NULL)
1523 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1524 if ((rc = mdb_touch(txn, mpp)) != 0)
1526 dh = ((MDB_dhead *)mpp->mp_page)-1;
1527 dh->md_parent = mpp->mp_parent;
1528 dh->md_pi = mpp->mp_pi;
1535 DPRINTF("internal error, index points to a %02X page!?",
1540 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1541 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1546 /* Search for the page a given key should be in.
1547 * Stores a pointer to the found page in *mpp.
1548 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1549 * If cursor is non-null, pushes parent pages on the cursor stack.
1550 * If modify is true, visited pages are updated with new page numbers.
1553 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1554 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1559 /* Choose which root page to start with. If a transaction is given
1560 * use the root page from the transaction, otherwise read the last
1561 * committed root page.
1563 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1564 DPRINTF("transaction has failed, must abort");
1567 root = txn->mt_dbs[dbi].md_root;
1569 if (root == P_INVALID) { /* Tree is empty. */
1570 DPRINTF("tree is empty");
1574 if ((mpp->mp_page = mdbenv_get_page(txn->mt_env, root)) == NULL)
1577 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1580 /* For sub-databases, update main root first */
1581 if (dbi > MAIN_DBI && txn->mt_dbs[dbi].md_root ==
1582 txn->mt_env->me_dbs[txn->mt_env->me_db_toggle][dbi].md_root) {
1584 rc = mdb_search_page(txn, 0, &txn->mt_dbxs[dbi].md_name,
1589 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1590 mpp->mp_parent = NULL;
1592 if ((rc = mdb_touch(txn, mpp)))
1594 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1598 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1602 mdb_read_data(MDB_env *env, MDB_node *leaf, MDB_val *data)
1604 MDB_page *omp; /* overflow mpage */
1607 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1608 data->mv_size = leaf->mn_dsize;
1609 data->mv_data = NODEDATA(leaf);
1613 /* Read overflow data.
1615 data->mv_size = leaf->mn_dsize;
1616 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1617 if ((omp = mdbenv_get_page(env, pgno)) == NULL) {
1618 DPRINTF("read overflow page %lu failed", pgno);
1621 data->mv_data = omp;
1627 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1628 MDB_val *key, MDB_val *data)
1636 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1638 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1642 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1645 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1647 rc = mdb_read_data(txn->mt_env, leaf, data);
1656 mdb_sibling(MDB_cursor *cursor, int move_right)
1660 MDB_ppage *parent, *top;
1663 top = CURSOR_TOP(cursor);
1664 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1665 return ENOENT; /* root has no siblings */
1668 DPRINTF("parent page is page %lu, index %u",
1669 parent->mp_page->mp_pgno, parent->mp_ki);
1671 cursor_pop_page(cursor);
1672 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1673 : (parent->mp_ki == 0)) {
1674 DPRINTF("no more keys left, moving to %s sibling",
1675 move_right ? "right" : "left");
1676 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1678 parent = CURSOR_TOP(cursor);
1684 DPRINTF("just moving to %s index key %u",
1685 move_right ? "right" : "left", parent->mp_ki);
1687 assert(IS_BRANCH(parent->mp_page));
1689 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1690 if ((mp = mdbenv_get_page(cursor->mc_txn->mt_env, indx->mn_pgno)) == NULL)
1693 mp->parent = parent->mp_page;
1694 mp->parent_index = parent->mp_ki;
1697 cursor_push_page(cursor, mp);
1703 mdb_set_key(MDB_node *node, MDB_val *key)
1708 key->mv_size = node->mn_ksize;
1709 key->mv_data = NODEKEY(node);
1715 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1721 if (cursor->mc_eof) {
1725 assert(cursor->mc_initialized);
1727 top = CURSOR_TOP(cursor);
1730 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1732 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1733 DPRINTF("=====> move to next sibling page");
1734 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1738 top = CURSOR_TOP(cursor);
1740 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1744 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1745 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1747 assert(IS_LEAF(mp));
1748 leaf = NODEPTR(mp, top->mp_ki);
1750 if (data && mdb_read_data(cursor->mc_txn->mt_env, leaf, data) != MDB_SUCCESS)
1753 return mdb_set_key(leaf, key);
1757 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1767 assert(key->mv_size > 0);
1769 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1770 if (rc != MDB_SUCCESS)
1772 assert(IS_LEAF(mpp.mp_page));
1774 top = CURSOR_TOP(cursor);
1775 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1776 if (exactp != NULL && !*exactp) {
1777 /* MDB_SET specified and not an exact match. */
1782 DPRINTF("===> inexact leaf not found, goto sibling");
1783 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1784 return rc; /* no entries matched */
1785 top = CURSOR_TOP(cursor);
1787 mpp.mp_page = top->mp_page;
1788 assert(IS_LEAF(mpp.mp_page));
1789 leaf = NODEPTR(mpp.mp_page, 0);
1792 cursor->mc_initialized = 1;
1795 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1798 rc = mdb_set_key(leaf, key);
1799 if (rc == MDB_SUCCESS) {
1800 DPRINTF("==> cursor placed on key %.*s",
1801 (int)key->mv_size, (char *)key->mv_data);
1809 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1815 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1816 if (rc != MDB_SUCCESS)
1818 assert(IS_LEAF(mpp.mp_page));
1820 leaf = NODEPTR(mpp.mp_page, 0);
1821 cursor->mc_initialized = 1;
1824 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1827 return mdb_set_key(leaf, key);
1831 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1838 lkey.mv_size = MAXKEYSIZE+1;
1839 lkey.mv_data = NULL;
1841 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
1842 if (rc != MDB_SUCCESS)
1844 assert(IS_LEAF(mpp.mp_page));
1846 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
1847 cursor->mc_initialized = 1;
1850 if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1853 return mdb_set_key(leaf, key);
1857 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1868 while (CURSOR_TOP(cursor) != NULL)
1869 cursor_pop_page(cursor);
1870 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1872 } else if (op == MDB_SET)
1873 rc = mdb_cursor_set(cursor, key, data, &exact);
1875 rc = mdb_cursor_set(cursor, key, data, NULL);
1878 if (!cursor->mc_initialized)
1879 rc = mdb_cursor_first(cursor, key, data);
1881 rc = mdb_cursor_next(cursor, key, data);
1884 while (CURSOR_TOP(cursor) != NULL)
1885 cursor_pop_page(cursor);
1886 rc = mdb_cursor_first(cursor, key, data);
1889 while (CURSOR_TOP(cursor) != NULL)
1890 cursor_pop_page(cursor);
1891 rc = mdb_cursor_last(cursor, key, data);
1894 DPRINTF("unhandled/unimplemented cursor operation %u", op);
1902 /* Allocate a page and initialize it
1905 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
1909 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
1911 DPRINTF("allocated new mpage %lu, page size %u",
1912 dp->p.mp_pgno, txn->mt_env->me_psize);
1913 dp->p.mp_flags = flags | P_DIRTY;
1914 dp->p.mp_lower = PAGEHDRSZ;
1915 dp->p.mp_upper = txn->mt_env->me_psize;
1917 if (IS_BRANCH(&dp->p))
1918 txn->mt_dbs[dbi].md_branch_pages++;
1919 else if (IS_LEAF(&dp->p))
1920 txn->mt_dbs[dbi].md_leaf_pages++;
1921 else if (IS_OVERFLOW(&dp->p)) {
1922 txn->mt_dbs[dbi].md_overflow_pages += num;
1923 dp->p.mp_pages = num;
1930 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
1934 sz = LEAFSIZE(key, data);
1935 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
1936 /* put on overflow page */
1937 sz -= data->mv_size - sizeof(pgno_t);
1940 return sz + sizeof(indx_t);
1944 mdb_branch_size(MDB_env *env, MDB_val *key)
1949 if (sz >= env->me_psize / MDB_MINKEYS) {
1950 /* put on overflow page */
1951 /* not implemented */
1952 /* sz -= key->size - sizeof(pgno_t); */
1955 return sz + sizeof(indx_t);
1959 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
1960 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
1963 size_t node_size = NODESIZE;
1966 MDB_dpage *ofp = NULL; /* overflow page */
1968 assert(mp->mp_upper >= mp->mp_lower);
1970 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
1971 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
1972 IS_LEAF(mp) ? "leaf" : "branch",
1973 mp->mp_pgno, indx, key ? key->mv_size : 0);
1976 node_size += key->mv_size;
1980 if (F_ISSET(flags, F_BIGDATA)) {
1981 /* Data already on overflow page. */
1982 node_size += sizeof(pgno_t);
1983 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
1984 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
1985 /* Put data on overflow page. */
1986 DPRINTF("data size is %zu, put on overflow page",
1988 node_size += sizeof(pgno_t);
1989 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
1991 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
1994 node_size += data->mv_size;
1998 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
1999 DPRINTF("not enough room in page %lu, got %u ptrs",
2000 mp->mp_pgno, NUMKEYS(mp));
2001 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2002 mp->mp_upper - mp->mp_lower);
2003 DPRINTF("node size = %zu", node_size);
2007 /* Move higher pointers up one slot. */
2008 for (i = NUMKEYS(mp); i > indx; i--)
2009 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2011 /* Adjust free space offsets. */
2012 ofs = mp->mp_upper - node_size;
2013 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2014 mp->mp_ptrs[indx] = ofs;
2016 mp->mp_lower += sizeof(indx_t);
2018 /* Write the node data. */
2019 node = NODEPTR(mp, indx);
2020 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2021 node->mn_flags = flags;
2023 node->mn_dsize = data->mv_size;
2025 node->mn_pgno = pgno;
2028 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2033 if (F_ISSET(flags, F_BIGDATA))
2034 memcpy(node->mn_data + key->mv_size, data->mv_data,
2037 memcpy(node->mn_data + key->mv_size, data->mv_data,
2040 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2042 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2050 mdb_del_node(MDB_page *mp, indx_t indx)
2053 indx_t i, j, numkeys, ptr;
2057 DPRINTF("delete node %u on %s page %lu", indx,
2058 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2059 assert(indx < NUMKEYS(mp));
2061 node = NODEPTR(mp, indx);
2062 sz = NODESIZE + node->mn_ksize;
2064 if (F_ISSET(node->mn_flags, F_BIGDATA))
2065 sz += sizeof(pgno_t);
2067 sz += NODEDSZ(node);
2070 ptr = mp->mp_ptrs[indx];
2071 numkeys = NUMKEYS(mp);
2072 for (i = j = 0; i < numkeys; i++) {
2074 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2075 if (mp->mp_ptrs[i] < ptr)
2076 mp->mp_ptrs[j] += sz;
2081 base = (char *)mp + mp->mp_upper;
2082 memmove(base + sz, base, ptr - mp->mp_upper);
2084 mp->mp_lower -= sizeof(indx_t);
2089 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2093 if (txn == NULL || ret == NULL)
2096 if ((cursor = calloc(1, sizeof(*cursor))) != NULL) {
2097 SLIST_INIT(&cursor->mc_stack);
2098 cursor->mc_dbi = dbi;
2099 cursor->mc_txn = txn;
2108 mdb_cursor_close(MDB_cursor *cursor)
2110 if (cursor != NULL) {
2111 while (!CURSOR_EMPTY(cursor))
2112 cursor_pop_page(cursor);
2114 /* btree_close(cursor->bt); */
2120 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2122 indx_t ptr, i, numkeys;
2128 node = NODEPTR(mp, indx);
2129 ptr = mp->mp_ptrs[indx];
2130 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2132 (int)node->mn_ksize, (char *)NODEKEY(node),
2133 (int)key->mv_size, (char *)key->mv_data,
2136 delta = key->mv_size - node->mn_ksize;
2138 if (delta > 0 && SIZELEFT(mp) < delta) {
2139 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2143 numkeys = NUMKEYS(mp);
2144 for (i = 0; i < numkeys; i++) {
2145 if (mp->mp_ptrs[i] <= ptr)
2146 mp->mp_ptrs[i] -= delta;
2149 base = (char *)mp + mp->mp_upper;
2150 len = ptr - mp->mp_upper + NODESIZE;
2151 memmove(base - delta, base, len);
2152 mp->mp_upper -= delta;
2154 node = NODEPTR(mp, indx);
2155 node->mn_ksize = key->mv_size;
2158 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2163 /* Move a node from src to dst.
2166 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2167 MDB_pageparent *dst, indx_t dstindx)
2173 srcnode = NODEPTR(src->mp_page, srcindx);
2174 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2175 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2177 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2178 src->mp_page->mp_pgno,
2179 dstindx, dst->mp_page->mp_pgno);
2181 /* Mark src and dst as dirty. */
2182 if ((rc = mdb_touch(txn, src)) ||
2183 (rc = mdb_touch(txn, dst)))
2186 /* Add the node to the destination page.
2188 key.mv_size = srcnode->mn_ksize;
2189 key.mv_data = NODEKEY(srcnode);
2190 data.mv_size = NODEDSZ(srcnode);
2191 data.mv_data = NODEDATA(srcnode);
2192 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2194 if (rc != MDB_SUCCESS)
2197 /* Delete the node from the source page.
2199 mdb_del_node(src->mp_page, srcindx);
2201 /* Update the parent separators.
2203 if (srcindx == 0 && src->mp_pi != 0) {
2204 DPRINTF("update separator for source page %lu to [%.*s]",
2205 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2206 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2207 &key)) != MDB_SUCCESS)
2211 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2213 nullkey.mv_size = 0;
2214 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2217 if (dstindx == 0 && dst->mp_pi != 0) {
2218 DPRINTF("update separator for destination page %lu to [%.*s]",
2219 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2220 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2221 &key)) != MDB_SUCCESS)
2225 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2227 nullkey.mv_size = 0;
2228 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2235 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2244 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2246 assert(txn != NULL);
2247 assert(src->mp_parent); /* can't merge root page */
2248 assert(dst->mp_parent);
2250 /* Mark src and dst as dirty. */
2251 if ((rc = mdb_touch(txn, src)) ||
2252 (rc = mdb_touch(txn, dst)))
2255 /* Move all nodes from src to dst.
2257 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2258 srcnode = NODEPTR(src->mp_page, i);
2260 key.mv_size = srcnode->mn_ksize;
2261 key.mv_data = NODEKEY(srcnode);
2262 data.mv_size = NODEDSZ(srcnode);
2263 data.mv_data = NODEDATA(srcnode);
2264 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2265 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2266 if (rc != MDB_SUCCESS)
2270 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2271 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2273 /* Unlink the src page from parent.
2275 mdb_del_node(src->mp_parent, src->mp_pi);
2276 if (src->mp_pi == 0) {
2278 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2282 if (IS_LEAF(src->mp_page))
2283 txn->mt_dbs[dbi].md_leaf_pages--;
2285 txn->mt_dbs[dbi].md_branch_pages--;
2287 mpp.mp_page = src->mp_parent;
2288 dh = (MDB_dhead *)src->mp_parent;
2290 mpp.mp_parent = dh->md_parent;
2291 mpp.mp_pi = dh->md_pi;
2293 return mdb_rebalance(txn, dbi, &mpp);
2296 #define FILL_THRESHOLD 250
2299 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2304 indx_t si = 0, di = 0;
2306 assert(txn != NULL);
2307 assert(mpp != NULL);
2309 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2310 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2311 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2313 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2314 DPRINTF("no need to rebalance page %lu, above fill threshold",
2315 mpp->mp_page->mp_pgno);
2319 if (mpp->mp_parent == NULL) {
2320 if (NUMKEYS(mpp->mp_page) == 0) {
2321 DPRINTF("tree is completely empty");
2322 txn->mt_dbs[dbi].md_root = P_INVALID;
2323 txn->mt_dbs[dbi].md_depth--;
2324 txn->mt_dbs[dbi].md_leaf_pages--;
2325 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2326 DPRINTF("collapsing root page!");
2327 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2328 if ((root = mdbenv_get_page(txn->mt_env, txn->mt_dbs[dbi].md_root)) == NULL)
2330 txn->mt_dbs[dbi].md_depth--;
2331 txn->mt_dbs[dbi].md_branch_pages--;
2333 DPRINTF("root page doesn't need rebalancing");
2337 /* The parent (branch page) must have at least 2 pointers,
2338 * otherwise the tree is invalid.
2340 assert(NUMKEYS(mpp->mp_parent) > 1);
2342 /* Leaf page fill factor is below the threshold.
2343 * Try to move keys from left or right neighbor, or
2344 * merge with a neighbor page.
2349 if (mpp->mp_pi == 0) {
2350 /* We're the leftmost leaf in our parent.
2352 DPRINTF("reading right neighbor");
2353 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2354 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2356 npp.mp_pi = mpp->mp_pi + 1;
2358 di = NUMKEYS(mpp->mp_page);
2360 /* There is at least one neighbor to the left.
2362 DPRINTF("reading left neighbor");
2363 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2364 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2366 npp.mp_pi = mpp->mp_pi - 1;
2367 si = NUMKEYS(npp.mp_page) - 1;
2370 npp.mp_parent = mpp->mp_parent;
2372 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2373 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2375 /* If the neighbor page is above threshold and has at least two
2376 * keys, move one key from it.
2378 * Otherwise we should try to merge them.
2380 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2381 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2382 else { /* FIXME: if (has_enough_room()) */
2383 if (mpp->mp_pi == 0)
2384 return mdb_merge(txn, dbi, &npp, mpp);
2386 return mdb_merge(txn, dbi, mpp, &npp);
2391 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2395 /* add overflow pages to free list */
2396 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2400 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2401 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2402 for (i=0; i<ovpages; i++) {
2403 DPRINTF("freed ov page %lu", pg);
2404 mdb_idl_insert(txn->mt_free_pgs, pg);
2408 mdb_del_node(mpp->mp_page, ki);
2409 txn->mt_dbs[dbi].md_entries--;
2410 rc = mdb_rebalance(txn, dbi, mpp);
2411 if (rc != MDB_SUCCESS)
2412 txn->mt_flags |= MDB_TXN_ERROR;
2418 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2419 MDB_val *key, MDB_val *data)
2426 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2428 assert(key != NULL);
2430 if (txn == NULL || dbi >= txn->mt_numdbs)
2433 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2437 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2441 mpp.mp_parent = NULL;
2443 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2446 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2447 if (leaf == NULL || !exact) {
2451 if (data && (rc = mdb_read_data(txn->mt_env, leaf, data)) != MDB_SUCCESS)
2454 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2457 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2458 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2459 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2460 * refer to a node in the new right sibling page.
2463 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2464 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2467 int rc = MDB_SUCCESS, ins_new = 0;
2470 unsigned int i, j, split_indx;
2472 MDB_val sepkey, rkey, rdata;
2474 MDB_dpage *mdp, *rdp, *pdp;
2477 assert(txn != NULL);
2479 dh = ((MDB_dhead *)*mpp) - 1;
2480 mdp = (MDB_dpage *)dh;
2481 newindx = *newindxp;
2483 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2484 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2485 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2487 if (mdp->h.md_parent == NULL) {
2488 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2491 mdp->h.md_parent = &pdp->p;
2492 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2493 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2494 txn->mt_dbs[dbi].md_depth++;
2496 /* Add left (implicit) pointer. */
2497 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2498 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2501 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2504 /* Create a right sibling. */
2505 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2507 rdp->h.md_parent = mdp->h.md_parent;
2508 rdp->h.md_pi = mdp->h.md_pi + 1;
2509 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2511 /* Move half of the keys to the right sibling. */
2512 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2514 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2515 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2516 mdp->p.mp_lower = PAGEHDRSZ;
2517 mdp->p.mp_upper = txn->mt_env->me_psize;
2519 split_indx = NUMKEYS(copy) / 2 + 1;
2521 /* First find the separating key between the split pages.
2523 memset(&sepkey, 0, sizeof(sepkey));
2524 if (newindx == split_indx) {
2525 sepkey.mv_size = newkey->mv_size;
2526 sepkey.mv_data = newkey->mv_data;
2528 node = NODEPTR(copy, split_indx);
2529 sepkey.mv_size = node->mn_ksize;
2530 sepkey.mv_data = NODEKEY(node);
2533 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2535 /* Copy separator key to the parent.
2537 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2538 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2539 &sepkey, NULL, rdp->p.mp_pgno);
2541 /* Right page might now have changed parent.
2542 * Check if left page also changed parent.
2544 if (rdp->h.md_parent != mdp->h.md_parent &&
2545 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2546 mdp->h.md_parent = rdp->h.md_parent;
2547 mdp->h.md_pi = rdp->h.md_pi - 1;
2550 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2551 &sepkey, NULL, rdp->p.mp_pgno, 0);
2553 if (rc != MDB_SUCCESS) {
2558 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2559 if (i < split_indx) {
2560 /* Re-insert in left sibling. */
2563 /* Insert in right sibling. */
2564 if (i == split_indx)
2565 /* Reset insert index for right sibling. */
2566 j = (i == newindx && ins_new);
2570 if (i == newindx && !ins_new) {
2571 /* Insert the original entry that caused the split. */
2572 rkey.mv_data = newkey->mv_data;
2573 rkey.mv_size = newkey->mv_size;
2574 if (IS_LEAF(&mdp->p)) {
2575 rdata.mv_data = newdata->mv_data;
2576 rdata.mv_size = newdata->mv_size;
2583 /* Update page and index for the new key. */
2586 } else if (i == NUMKEYS(copy)) {
2589 node = NODEPTR(copy, i);
2590 rkey.mv_data = NODEKEY(node);
2591 rkey.mv_size = node->mn_ksize;
2592 if (IS_LEAF(&mdp->p)) {
2593 rdata.mv_data = NODEDATA(node);
2594 rdata.mv_size = node->mn_dsize;
2596 pgno = node->mn_pgno;
2597 flags = node->mn_flags;
2602 if (!IS_LEAF(&mdp->p) && j == 0) {
2603 /* First branch index doesn't need key data. */
2607 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2615 mdb_put(MDB_txn *txn, MDB_dbi dbi,
2616 MDB_val *key, MDB_val *data, unsigned int flags)
2618 int rc = MDB_SUCCESS, exact;
2623 assert(key != NULL);
2624 assert(data != NULL);
2629 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2633 if (txn->mt_env->me_txn != txn) {
2637 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2641 DPRINTF("==> put key %.*s, size %zu, data size %zu",
2642 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2644 mpp.mp_parent = NULL;
2646 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2647 if (rc == MDB_SUCCESS) {
2648 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2649 if (leaf && exact) {
2650 if (F_ISSET(flags, MDB_NOOVERWRITE)) {
2651 DPRINTF("duplicate key %.*s",
2652 (int)key->mv_size, (char *)key->mv_data);
2655 /* same size, just replace it */
2656 if (NODEDSZ(leaf) == data->mv_size) {
2657 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2660 mdb_del_node(mpp.mp_page, ki);
2662 if (leaf == NULL) { /* append if not found */
2663 ki = NUMKEYS(mpp.mp_page);
2664 DPRINTF("appending key at index %i", ki);
2666 } else if (rc == ENOENT) {
2668 /* new file, just write a root leaf page */
2669 DPRINTF("allocating new root leaf page");
2670 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2673 mpp.mp_page = &dp->p;
2674 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
2675 txn->mt_dbs[dbi].md_depth++;
2681 assert(IS_LEAF(mpp.mp_page));
2682 DPRINTF("there are %u keys, should insert new key at index %i",
2683 NUMKEYS(mpp.mp_page), ki);
2685 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2686 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2688 /* There is room already in this leaf page. */
2689 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2692 if (rc != MDB_SUCCESS)
2693 txn->mt_flags |= MDB_TXN_ERROR;
2695 txn->mt_dbs[dbi].md_entries++;
2702 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
2707 *arg = env->me_flags;
2712 mdbenv_get_path(MDB_env *env, const char **arg)
2717 *arg = env->me_path;
2722 mdbenv_stat(MDB_env *env, MDB_stat *arg)
2724 if (env == NULL || arg == NULL)
2727 arg->ms_psize = env->me_psize;
2728 arg->ms_depth = env->me_meta->mm_dbs[MAIN_DBI].md_depth;
2729 arg->ms_branch_pages = env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages;
2730 arg->ms_leaf_pages = env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages;
2731 arg->ms_overflow_pages = env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages;
2732 arg->ms_entries = env->me_meta->mm_dbs[MAIN_DBI].md_entries;
2737 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
2750 /* Is the DB already open? */
2752 for (i=2; i<txn->mt_numdbs; i++) {
2753 if (len == txn->mt_dbxs[i].md_name.mv_size &&
2754 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
2760 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
2763 /* Find the DB info */
2765 key.mv_data = (void *)name;
2766 rc = mdb_get(txn, MAIN_DBI, &key, &data);
2768 /* Create if requested */
2769 if (rc == ENOENT && (flags & MDB_CREATE)) {
2771 data.mv_size = sizeof(MDB_db);
2772 data.mv_data = &dummy;
2773 memset(&dummy, 0, sizeof(dummy));
2774 dummy.md_root = P_INVALID;
2775 dummy.md_flags = flags & 0xffff;
2776 rc = mdb_put(txn, 0, &key, &data, 0);
2779 /* OK, got info, add to table */
2780 if (rc == MDB_SUCCESS) {
2781 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
2782 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
2783 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
2784 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
2785 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
2786 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
2787 *dbi = txn->mt_numdbs;
2794 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
2796 if (txn == NULL || arg == NULL)
2799 arg->ms_psize = txn->mt_env->me_psize;
2800 arg->ms_depth = txn->mt_dbs[dbi].md_depth;
2801 arg->ms_branch_pages = txn->mt_dbs[dbi].md_branch_pages;
2802 arg->ms_leaf_pages = txn->mt_dbs[dbi].md_leaf_pages;
2803 arg->ms_overflow_pages = txn->mt_dbs[dbi].md_overflow_pages;
2804 arg->ms_entries = txn->mt_dbs[dbi].md_entries;
2809 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
2812 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
2814 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
2815 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
2816 txn->mt_dbxs[dbi].md_name.mv_size = 0;